Regex to find phone number with country code from string

Viewed 103

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!

1 Answers

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.

Related