2

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!

johnnasx
  • 158
  • 10
  • Perhaps this page can help you https://stackoverflow.com/questions/16699007/regular-expression-to-match-standard-10-digit-phone-number – The fourth bird May 29 '20 at 19:51
  • `/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/` – B001ᛦ May 29 '20 at 19:54
  • the expression from @Thefourthbird returns nothing as tested on https://www.phpliveregex.com/ when putting a number in a string context – johnnasx May 29 '20 at 19:59
  • the expression from @B001ᛦ also returns nothing when having a context like: xx +1 442-444-2222 sxxxxTEST – johnnasx May 29 '20 at 20:00

1 Answers1

0

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.

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37