简体   繁体   中英

get phone code from phone number using regex in php

I have 3-4 types of numbers ,i want to get phone code from the phone number using a regex.

Ex: +91 123456789 , +91123456789 , +123465789

But i want to extract code from this kind of numbers +91 123456789 with start with + sign and a space between number and phone code using a regex. I want a result only 91 .

I have tried from this SO answer , but this answer not contain regex for the phone code.

You could capture the phone code in a capturing group:

$re = '/^\+(\d+)/';
$str = '+91 123456789';

preg_match($re, $str, $matches);
var_dump($matches);

Your code will be in captured group 1.

Php demo output

To capture the plus sign, the phone code and the whitespace, you could use:

^(\\+)(\\d+)( )

No need of regex. Simply use explode() with an if-else

if(substr_count($phonenumber,' ') > 0){
   trim(explode(' ',$phonenumber)[0],'+');
}

Output:- https://eval.in/962973

Fore regex do like this:- https://eval.in/962999

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