mathceleb
04-01-2010, 03:54 PM
I want to load all successful matches into an array:
$text="(6-9)+9^2 + (35 + 8) * (2 - 6)/3";
preg_match('#\((.*)\)#', $text, $match);
print $match[0] . "<br />";
The above returns (6-9)+9^2 + (35 + 8) * (2 - 6).
How do I get an array with
$match[0]=(6-9)
$match[1]=(35 + 8)
$match[2]=(2 - 6)
kbluhm
04-01-2010, 04:22 PM
http://www.php.net/preg_match_all
preg_match_all( '#\(.+\)#U', $text, $matches );
The U modifier forces the regexp to be "ungreedy".
Or:
preg_match_all( '#\([^\)]+\)#', $text, $matches );
That will match anything starting with an open parenthesis, continuing through anything that is not a close parenthesis, till it finds a close parenthesis.
Then do a print_r( $matches ); to see what you're able to work with. You'll want to use preg_match_all() to find all matches, as opposed to preg_match(), which will stop searching at the first match.
mathceleb
04-01-2010, 04:33 PM
http://www.php.net/preg_match_all
preg_match_all( '#\(.+\)#U', $text, $matches );
The U modifier forces the regexp to be "ungreedy".
Or:
preg_match_all( '#\([^\)]+\)#', $text, $matches );
That will match anything starting with an open parenthesis, continuing through anything that is not a close parenthesis, till it finds a close parenthesis.
Then do a print_r( $matches ); to see what you're able to work with. You'll want to use preg_match_all() to find all matches, as opposed to preg_match(), which will stop searching at the first match.
Fantastic! I used the second code entry you supplied, along with:
echo $match[0][0] . "<br />";
echo $match[0][1] . "<br />";
Thanks again!