Page 1 of 1

looking for data around matches

Posted: Wed Aug 03, 2005 11:15 am
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?

Posted: Wed Aug 03, 2005 1:31 pm
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>';

assertions

Posted: Wed Aug 03, 2005 1:35 pm
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.