Click to See Complete Forum and Search --> : preg_match_all finds only 1??
mitya
12-08-2005, 09:09 AM
Can anyone help with this? I'm trying to find all occurrances of a regular expression in a string and put out the results to an array. I've tried using eregi and preg_match_all and every time it only finds one result.
Example of what to find: {-libItem29-}
Reg ex: "{-libItem[0-9]{0,}-}"
Am I missing something that makes it global? I thought preg_match_all was global by definition.
Thanks in advance.
bokeh
12-08-2005, 09:12 AM
Post your code! In particular the regular expession and the target string.
mitya
12-08-2005, 09:27 AM
$string = "{-libItem28-} (part of string not to be matched) {-libItem29-}";
preg_match_all("{-libItem[0-9]{0,}-}", $string, $matches);
echo count($matches);
//always puts out 1, even though there are clearly two instances of reg ex.
bokeh
12-08-2005, 09:38 AM
//always puts out 1, even though there are clearly two instances of reg ex. That's correct. $matches[0] is the array containing all the global matches. So if you said echo count($matches[0]); it would return the number of matches. Example:<?php
$string = "{-libItem28-} (part of string not to be matched) {-libItem29-}";
preg_match_all("#{-libItem[0-9]{0,}-}#", $string, $matches);
echo count($matches[0]);
?>
ShrineDesigns
12-08-2005, 09:39 AM
you need to escape things like {}()[]-.+?\/$^ etc as those characters have special meaning in regular expressions
RegExp\{\-libitem[0-9]+\-\}
bokeh
12-08-2005, 09:42 AM
you need to escape things like {}()[]-.+?\/$^ etc as those characters have special meaning in regular expressions
RegExp\{\-libitem[0-9]+\-\}You don't need to escape them globally, only if necessary. The regex posted works just fine.
ShrineDesigns
12-08-2005, 09:54 AM
i did see your post, i must posted my comment shortly after you did lol
the #...# is quite handy
mitya
12-08-2005, 09:55 AM
Thanks guys. I eventually realised that everything was getting chucked into $array[0] - I guess I should have read the PHP manual page better.
As for escaping: yeah I expected I'd have to, but as bokeh says, it seems to work without having to.
Cheers again.