учитывая, что строка
$opStr = "1 + 2 - 3 * 4 / 5";
preg_match('/[\+\-\*\/]/', $strOp, $matches);
$ матчи
array (size=1)
0 => string '+' (length=1)
в основном это соответствует первому операнду, есть ли способ узнать, содержит ли строка больше операнда, как в этом примере?
благодаря
ожидаемые результаты
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('+', '-', '+', '/')
Для выполнения глобального соответствия вам необходимо использовать preg_match_all
.
preg_match_all('~[-+*/]~', $strOp, $matches);
$re = "~[-+*/]~m";
$str = "1 + 2 - 3 * 4 / 5";
preg_match_all($re, $str, $matches);
print_r($matches);
Вывод:
Array
(
[0] => Array
(
[0] => +
[1] => -
[2] => *
[3] => /
)
)
Просто используйте preg_match_all вместо 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] => /
)
)
*/