简体   繁体   中英

Regex to find phone number with country code from string

I currently have the following:

    preg_match_all('/\b[0-9]{3}\s*-\s*[0-9]{3}\s*-\s*[0-9]{4}\b/',$cacax,$matches);
    echo '<pre>';
    print_r($matches[0]);

This will output:

[0] => 888-618-0367

instead of

 [0] => +1 888-618-0367

I got no clue on how to make that regex expression only match +1 starting numbers and also include the number in the match.

Will appreciate any help, thanks!

Add \+1\s* at the start, use

\+1\s*[0-9]{3}\s*-\s*[0-9]{3}\s*-\s*[0-9]{4}\b

See proof . The \+1\s* part will require +1 and zero or more whitespace characters at the start of your matches.

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