简体   繁体   中英

check 10 digit mobile number in string using php

I want to check 10 digit number in following strings using php

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

when find 10 digit number then return true

You can use 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

In order to only match exact 10 digits you need to combine the {} with the \\b in the regex pattern.
{} specifies the number of digits and \\b means match complete words.

In this example only the last string should return 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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