tags:

views:

122

answers:

4

Hi all, 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"
+2  A: 
/(?:(?:^|\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.

J-P
@Johnsyweb, Sorry. Fixed.
J-P
@Johnsyweb: It will because of "one four six nine".
Mark Byers
thanks will this handle spaces between the words ?
Sherif Omar
@Sherif, yes. Note that you'll need to put the regex in a string (`"/.../"`), and you'll probably need to escape the `\s` (=>`\\s`).
J-P
thanks a million man.
Sherif Omar
Allowed numbers are from zero to nine but not ten
M42
+2  A: 

You can do it like this:

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

(Rubular)

Mark Byers
A: 
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.

Pavel Nikolov
Aren't you missing spaces between the words?
Kobi
+2  A: 

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)

Kobi
+1 I quite like this approach. Here's a Rubular link for it: http://rubular.com/r/Fm4dGwkNGg ... You forgot zero though.
Mark Byers
@Mark - Thanks. I tested it there too, just forgot the link. I have zero, but it isn't sorted `:)`
Kobi
@Kobi: Oh yeah, it's sorted in keyboard order. I should have noticed that zero is one of the examples in the rubular link. Sorry. :)
Mark Byers