所以基本上我需要检查一个字符串是否有3组或更多的分隔数字,例如:
words1 words2 111 222 333 //> YES, it has 3 groups of digits (separated by space)
words 1 2 //> NO
words 2011 words2 2012 2013 //> YES
我在想类似的东西
preg_match('/('b'd+'b){3,}/',$string)
但它根本不起作用(总是返回false)
感谢@Basti我现在使用这个正则表达式:
'/('D*'d+'D*){3,}/'
您可以使用此正则表达式来确保字符串中至少有3个数字:
#(?:'b'd+'b.*?){3}#
测试:
$arr = array(
'words1 words2 111 222 333',
'words 1 2',
'words 2011 words2 2012 2013',
'1 2 3',
'1 2 ab1',);
foreach ($arr as $u) {
echo "$u => ";
if (preg_match('#(?:'b'd+'b.*?){3}#', $u, $m))
var_dump($m[0]);
else
echo " NO MATCH'n";
}
输出:
words1 words2 111 222 333 => string(11) "111 222 333"
words 1 2 => NO MATCH
words 2011 words2 2012 2013 => string(21) "2011 words2 2012 2013"
1 2 3 => string(5) "1 2 3"
1 2 ab1 => NO MATCH
$non_numeric = array_filter(
array_filter(explode(' ', $string)),
function($c){
return !is_numeric($c);
});
if(count($non_numeric)) {
//YES
}
您的正则表达式说"至少查找一个或多个数字三次"。你真正想要的是:"找到两个或多个被我不在乎的东西包围的数字,至少三次。":
preg_match("/('D*'d{2,}'D*){3,}/", $string)
表达式的问题在于,除了数字和单词边界之外,不允许任何其他内容。
测试:三根琴弦上的var_dump(preg_match('/('D*'d{2,}'D*){3,}/',$string, $match), $match);
。
int 1
array
0 => string ' 111 222 333' (length=12)
1 => string '333' (length=3)
int 0
array
empty
int 1
array
0 => string ' 2012 2013' (length=10)
1 => string '13' (length=2)
是123注:
我正在使用我写的这个功能,它可以检查任何数量的组:
function countDigits($haystack) {
preg_match_all('/'b'd+'b/',$haystack,$matches);
return count($matches[0]);
}
echo countDigits('2011 abc 2012'); //> prints 2