Reputation: 1983
given that string
$opStr = "1 + 2 - 3 * 4 / 5";
preg_match('/[\+\-\*\/]/', $strOp, $matches);
$matches is
array (size=1)
0 => string '+' (length=1)
basically it is matching the first operand, is there a way to know if the string contains more operand, like in this example?
thanks
expected outputs
case "1 + 1": $matches[0] = '+'
case "2 - 1": $matches[0] = '-'
case "1 + 2 - 3 * 4 / 5": $matches[0] = '+-+/'
or
case "1 + 2 - 3 * 4 / 5": $matches[0] = array('+', '-', '+', '/')
Upvotes: 0
Views: 170
Reputation: 364
Just use preg_match_all instead of preg_match.
<?php
$opStr = "1 + 2 - 3 * 4 / 5";
preg_match_all('/[\+\-\*\/]/', $opStr, $matches);
echo '<pre>';print_r($matches);echo '</pre>';
## will produce:
/*
Array
(
[0] => Array
(
[0] => +
[1] => -
[2] => *
[3] => /
)
)
*/
Upvotes: 0
Reputation: 174696
You need to use preg_match_all
function in-order to do a global match.
preg_match_all('~[-+*/]~', $strOp, $matches);
$re = "~[-+*/]~m";
$str = "1 + 2 - 3 * 4 / 5";
preg_match_all($re, $str, $matches);
print_r($matches);
Output:
Array
(
[0] => Array
(
[0] => +
[1] => -
[2] => *
[3] => /
)
)
Upvotes: 1