Search code examples
phpregexphone-numberdigits

php regex split string with phone numbers to a few elements in the array


How split string with phone numbers to a few elements in the array?

For example, we have string like this: "phone" => "+7 (343) 228-02-08 +7 (343) 203-209-3" or "phone" => "8 (800) 555-92-86 8 (499) 322-16-40 8 (812) 426-10-38"

But we need to make it:

"phone" => [
     "0" => "+7 (343) 228-02-08",
     "1" => "+7 (343) 203-209-3",
]

and for another

"phone" => [
    "0" => "8 (800) 555-92-86 8",
    "1" => "8 (499) 322-16-40",
    "2" => "8 (812) 426-10-38",
]

I tried to find some ready-made solutions, but nothing could be found. Regular expressions - is too complicated for me ...


Solution

  • Instead of split you can use matching using preg_match_all function using this regex:

    /\+?\d\h*\(\d{3}\)\h*[\d-]+/
    

    RegEx Demo