开发者

regular expression to detect numbers written as words

开发者 https://www.devze.com 2023-01-14 12:12 出处:网络
I need PHP code to detect whether a string contains 4 or more consecutive written numbers (0 to 9), like :

I need PHP code to detect whether a string contains 4 or more consecutive written numbers (0 to 9), like :

"one four six nine five"

or

"zero eight nine nine seven three s开发者_如何学JAVAix six"


You can do it like this:

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

(Rubular)


Another option is:

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

That's pretty much the same as the rest. The only interesting bit is the \s*? part - that will lazily match the spaces between the words, so you don't end up with extra spaces after the sequence of 4 words. The \b before it assures there's at least a single space (or other separator after the last word, so !a b c d! will match)


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

PHP code:

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

Note: More words (e.g. 'twelve') can easily be added to the regex.


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(s) in the regular expression - thanks to Kobi.

0

精彩评论

暂无评论...
验证码 换一张
取 消