I need PHP code to detect whether a string contains 4 or more consecutive written numbers (0 to 9), like :
我需要PHP代码来检测字符串是否包含4个或更多连续写入的数字(0到9),如:
"one four six nine five"
or
要么
"zero eight nine nine seven three six six"
4 个解决方案
#1
5
You can do it like this:
你可以这样做:
\b(?:(?:zero|one|two|three|four|five|six|seven|eight|nine)(?: +|$)){4}
(Rubular)
#2
3
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 *? part - 将懒惰地匹配单词之间的空格,因此在4个单词的序列之后你不会得到额外的空格。之前的\ b确保至少有一个空格(或者在最后一个单词之后的其他分隔符,所以!a b c d!将匹配)
#3
2
/(?:(?:^|\s)(?:one|two|three|four|five|six|seven|eight|nine|ten)(?=\s|$)){4,}/
PHP code:
PHP代码:
if (preg_match(...put regex here..., $stringToTestAgainst)) {
// ...
}
Note: More words (e.g. 'twelve') can easily be added to the regex.
注意:可以很容易地将更多单词(例如'12')添加到正则表达式中。
#4
0
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.
在正则表达式中添加了空格 - 感谢Kobi。
#1
5
You can do it like this:
你可以这样做:
\b(?:(?:zero|one|two|three|four|five|six|seven|eight|nine)(?: +|$)){4}
(Rubular)
#2
3
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 *? part - 将懒惰地匹配单词之间的空格,因此在4个单词的序列之后你不会得到额外的空格。之前的\ b确保至少有一个空格(或者在最后一个单词之后的其他分隔符,所以!a b c d!将匹配)
#3
2
/(?:(?:^|\s)(?:one|two|three|four|five|six|seven|eight|nine|ten)(?=\s|$)){4,}/
PHP code:
PHP代码:
if (preg_match(...put regex here..., $stringToTestAgainst)) {
// ...
}
Note: More words (e.g. 'twelve') can easily be added to the regex.
注意:可以很容易地将更多单词(例如'12')添加到正则表达式中。
#4
0
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.
在正则表达式中添加了空格 - 感谢Kobi。