looking for data around matches

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
jaymoore_299
Forum Contributor
Posts: 128
Joined: Wed May 11, 2005 6:40 pm
Contact:

looking for data around matches

Post by jaymoore_299 »

I am wondering if this is possible with regex.

I want to be able look to the left or right of a certain pattern match, such as "hat" and return matches to the left of it so that for the following text:
"red hat
blue hat
green hat"
the array (red, blue, green) would be returned.

How would I go about this? Also how would I do this for the right side?
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

Code: Select all

$str = "red hat
blue hat
green hat";
preg_match_all("/(^|.*?)hat(.*?|$)/i", $str, $matches);

echo '<pre>';
print_r($matches[1]);
print_r($matches[2]);
echo '</pre>';
yakasha
Forum Newbie
Posts: 10
Joined: Wed Aug 03, 2005 1:17 pm
Location: Las Vegas, NV
Contact:

assertions

Post by yakasha »

You could use assertions. Full instructions can be found here.

Basically, assertions match like anything else, but are not included in the returned match.
To find the word immediately before 'hat', you would use something like:
\w+\b(?= hat)

So:

Code: Select all

preg_match_all( "/\w+\b(?= hat)/", "red hat blue hat green hat", $matches );
should basically get you what you want.
Post Reply