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?
looking for data around matches
Moderator: General Moderators
-
jaymoore_299
- Forum Contributor
- Posts: 128
- Joined: Wed May 11, 2005 6:40 pm
- Contact:
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
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:
should basically get you what you want.
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 );