我想使用php检查以下字符串中的10位数字
$str1 = "when an unknown 8109100000 remaining essentially unchanged.";
$str2 = "when an unknown remaining essentially unchanged.";
找到10位数字后返回true
答案 0 :(得分:1)
您可以使用 preg_match
代码
$str1 = "when an unknown 8109100000 remaining essentially unchanged.";
$str2 = "when an unknown remaining essentially unchanged.";
$pattern = "/\b\d{10}\b/";
$isNum = preg_match($pattern,$str1, $match); //return 1 $str2 return 0.
if($isNum){
//Do something
}
else{
//Aww.... No number in string.
}
echo $match[0]; //return matched number.
详细了解preg_match Regex
答案 1 :(得分:1)
要只匹配精确的10位数字,您需要在正则表达式模式中将{}
与\b
组合在一起。
{}
指定位数,\b
表示匹配的完整单词。
在此示例中,仅最后一个字符串应返回true / 1。
$str = ["when an unknown 810910000011 remaining essentially unchanged.",
"when an unknown remaining essentially unchanged.",
"when an unknown 8109100000 remaining essentially unchanged."];
Foreach($str as $s){
Echo preg_match("/\b\d{10}\b/", $s) . "\n";
}
它输出
0
0
1
符合预期