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 six six"
The regular expression \b[A]\w+ can be used to find all words in the text which start with A. The \b means to begin searching for matches at the beginning of words, the [A] means that these matches start with the letter A, and the \w+ means to match one or more word characters.
The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With