Regex scenarios to Match International Phone Numbers in PHP - implementing Optional Prefixes
I tried several approaches but none seem to work. I'm testing a new approach and I'm having trouble crafting a regular expression to match international phone numbers in PHP. I want to accommodate various formats, including optional country codes and prefixes. For example, I want to match numbers like `+1 234-567-8901`, `001 234 567 8901`, and even `2345678901`. I've tried using the following regex: ```php $pattern = '/^(\+\d{1,3} ?|0{1,2})?\s?\(?\d{1,4}\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}$/'; ``` However, I keep getting false negatives for some valid inputs. For instance, the number `+44 20 7946 0958` is not being matched, while numbers without a country code seem to work fine. When I test with the following code: ```php $test_numbers = [ '+1 234-567-8901', '001 234 567 8901', '2345678901', '+44 20 7946 0958', '02079460958', ]; foreach ($test_numbers as $number) { if (preg_match($pattern, $number)) { echo "$number is valid.\n"; } else { echo "$number is invalid.\n"; } } ``` I get `+44 20 7946 0958 is invalid` as the output. I'm aware that phone number formats can vary and might have different lengths, but I thought my regex was covering most cases. What am I missing? Is there a more reliable way to handle this without making the regex too complex? Any suggestions or improvements would be greatly appreciated! I recently upgraded to Php 3.10. Thanks in advance! For context: I'm using Php on CentOS. Thanks in advance!