i have a simple php example of using preg_match_all
$str = "
Line 1: This is a string
Line 2: [img] image_path [/img] Should not be [img] image_path2 [/img] included.
Line 3: End of test [img] image_path3 [/img] string.";
preg_match_all("~\[img](.+)\[/img]~i", $str, $m);
var_dump($m);
and i would like it to return
array(
[0] =>image_path
[1] =>image_path2
[2] =>image_path3
)
for some reason i don’t get this result.
ant ideas?
Change it to this:
The reason you need the
?is to make it “non-greedy”. With your code, it matches from the first opening tag to the last closing tag. The+and*operators are greedy by default, consuming as many characters as possible. The?modifier stops this behaviour.You need to dump
$m[1]instead of$msincepreg_match*also matches the entire matched string, not just marked captures.Live example: http://ideone.com/vXk9W