PHP:如何使用正则表达式匹配字符串中的多个字符


php: how to match multiple chars in a string using regex

给定该字符串

$opStr = "1 + 2 - 3 * 4 / 5";
preg_match('/['+'-'*'/]/', $strOp, $matches);

$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] => /
    )
)
*/