I want the ability to look into a string and find all occurrences of a pattern. This is easy to do with preg_match if you know how many occurrences of the pattern to occur but I can’t figure out a way to get this to work when number of occurrences is not known.
Here’s an example of a working query for a know set of occurrences:
$pattern = '/\[VAR:(.*)\].*\[VAR:(.*)\].*\[VAR:(.*)\].*\[VAR:(.*)\]/';
$string = "[VAR:one] once apon a time [VAR:two]. And then there was the time that [VAR:three] went to [VAR:four]";
preg_match ( $pattern , $string, $matches );
print_r ( $matches );
This returns the results you’d expect:
[0] => [VAR:one] once apon a time [VAR:two]. And then there was the time that [VAR:three] went to [VAR:four]
[1] => one
[2] => two
[3] => three
[4] => four
I’ve tried unsuccessfully variations of preg_match and preg_match_all with the pattern (both using and not using the PREG_OFFSET_CAPTURE parameter):
$pattern = '/\[VAR:(.*)\]/';
Any help would be greatly appreciated.
It works for me with the following pattern and
preg_match_allSee http://ideone.com/lGsHl for your modified example.
The
?after.*makes it non-greedy.