Regex Not Matching Phone Numbers with Country Codes in PHP - Issues with Optional Spaces
I'm having trouble with I'm working on a personal project and I've been banging my head against this for hours. I'm having trouble with a regex pattern in PHP that's supposed to match international phone numbers formatted with country codes. The format I'm trying to accommodate is `+CC (XXX) XXX-XXXX`, where `CC` is the country code, `XXX` is the area code, and `XXXX` is the local number. I also want to allow for optional spaces between these groups. Here's the regex I've been using: ```php $pattern = '/\+\d{1,3} ?\(?\d{1,3}\)? ?\d{3}-\d{4}/'; $testStrings = [ '+1 (202) 555-0173', '+44 20 7946 0958', '+49 (30) 12345678', '+91(987)6543210', '+33 1 70 18 99 00', '12345' ]; foreach ($testStrings as $string) { if (preg_match($pattern, $string)) { echo "$string is a valid phone number.\n"; } else { echo "$string is NOT a valid phone number.\n"; } } ``` However, I noticed that it's not matching some valid formats, especially when there are multiple spaces or no spaces between the parts. For example, `'+91(987)6543210'` should be matched, but it currently doesn't. When I run the above code, I get the following output: ``` +1 (202) 555-0173 is a valid phone number. +44 20 7946 0958 is a valid phone number. +49 (30) 12345678 is a valid phone number. +91(987)6543210 is NOT a valid phone number. +33 1 70 18 99 00 is a valid phone number. 12345 is NOT a valid phone number. ``` I tried changing the regex to make spaces optional around both the area code and between the country code and area code, but it hasn't improved the results. I would appreciate any suggestions on how to adjust my regex to correctly match all intended formats, including those without spaces. I'm using Php 3.11 in this project. Could someone point me to the right documentation? For context: I'm using Php on Windows 11. Any help would be greatly appreciated! I'd really appreciate any guidance on this. Is this even possible? For reference, this is a production web app. Could this be a known issue? I'd be grateful for any help.