简体   繁体   English

使用php检查字符串中的10位数字

[英]check 10 digit mobile number in string using php

I want to check 10 digit number in following strings using php 我想使用php在以下字符串中检查10位数字

$str1 = "when an unknown 8109100000 remaining essentially unchanged.";
$str2 = "when an unknown remaining essentially unchanged.";

when find 10 digit number then return true 找到10位数字后返回true

You can use preg_match 您可以使用preg_match

Code

    $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.

Demo 演示版

Read more about preg_match Regex 阅读有关preg_match正则 表达式的更多信息

In order to only match exact 10 digits you need to combine the {} with the \\b in the regex pattern. 为了只匹配精确的10位数字,您需要在正则表达式模式中将{}\\b组合在一起。
{} specifies the number of digits and \\b means match complete words. {}指定位数, \\b表示匹配完整的单词。

In this example only the last string should return true/1. 在此示例中,仅最后一个字符串应返回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";
}

And it outputs 它输出

0
0
1

As expected 符合预期

https://3v4l.org/QesPA https://3v4l.org/QesPA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM