Regular expression to detect numbers written as words

I need PHP code to determine if a string contains 4 or more consecutive written numbers (from 0 to 9), for example:

"one four six nine five" 

or

 "zero eight nine nine seven three six six" 
+6
php regex
source share
4 answers

You can do it as follows:

 \b(?:(?:zero|one|two|three|four|five|six|seven|eight|nine)(?: +|$)){4} 

(Rubular)

+4
source share

Another variant:

 \b(?:(?:one|two|three|four|five|six|seven|eight|nine|zero)\b\s*?){4} 

It is almost the same as the rest. The only interesting bit is the \s*? , which will lazily match spaces between words, so you won’t get any extra spaces after a four-word sequence. \b before it assures at least one space there (or another separator after the last word, so !abcd! will match)

+3
source share
 /(?:(?:^|\s)(?:one|two|three|four|five|six|seven|eight|nine|ten)(?=\s|$)){4,}/ 

PHP code:

 if (preg_match(...put regex here..., $stringToTestAgainst)) { // ... } 

Note. Additional words (for example, "twelve") can be easily added to the regular expression.

+2
source share
 if (preg_match("/(?:\b(?:(one)|(two)|(three)|(four)|(five)|(six)|(seven)|(eight)|(nine))\b\s*?){4,}/", $variable_to_test_against, $matches)) { echo "Match was found <br />"; echo $matches[0]; } 

EDIT:

Added space in regular expression - thanks to Kobe.

0
source share

All Articles