Preg_match to capture simple math problems

frosty

I have a preg_match() to try and capture math problems, but it's only working partially. While it capture the 'plus' and the last 'one', it doesn't capture the first 'one' for some reason. What am I doing wrong?

$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);
}

Result:

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

Expected Result:

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

You can put your current capturing group with all alternatives into another one, so you capture everything and don't overwrite it every time when you encounter something like 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

(Modifier x, just used for explanation and formatting)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related