Preg_match捕获简单的数学问题

时间:2016-04-04 19:43:50

标签: php regex string preg-match

我有preg_match()尝试捕获数学问题,但它只是部分工作。虽然它捕获了“加号”和最后一个“加号”,但由于某种原因它并没有捕获第一个“加号”。我究竟做错了什么?

$string = "one plus one";

if (preg_match("~([0-9]|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million|\-| )+(\+|\-|\*|\/|plus|add|minus|subtract|time|multiply|divide)([0-9]|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million|\-| )+~", $string, $match)) {    
    print_r($match);
}

结果:

Array ( [0] => one plus one [1] => [2] => plus [3] => one )

预期结果:

Array ( [0] => one plus one [1] => one [2] => plus [3] => one )

1 个答案:

答案 0 :(得分:0)

您可以将当前捕获组的所有替代项放入另一个替代项中,这样您就可以捕获所有内容,并且每次遇到类似twenty nine的内容时都不会覆盖它。

~
[+-]? #number sign e.g. +5 or -5
((?:\d|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million|-|\s)+) #numbers
([+*/-]|plus|add|minus|subtract|time|multiply|divide) #operation
\s*[+-]? #number sign e.g. +5 or -5
((?:\d|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million|-|\s)+) #numbers
~x

(修饰符x,仅用于解释和格式化)