Skip to content
Advertisement

preg_replace phone number sanitizing for international numbers

I have a snip of PHP code that we use to strip out spaces and non numericals from phone numbers in PHP which works great and it removes the leading 0 from the phone number as well:

substr(preg_replace('/[^0+a-zA-Z0-9]+/', '', $phone), 1);

However in some scenarios the leading number is not a 0 it will be a 1 and we don’t want them stripped.

so if the number was 0312345678 it needs the leading 0 stripped off If the number however was 1800123456 it should not strip the leading 1 from the number

how can I adjust the replace to not strip all 1st digits off and only strip it off if its a 0, while retaining the remaining preg_replace functions as currently using substr strips the first digit regardless of what it is?

Advertisement

Answer

You can use

$phone = preg_replace('/^0|[^a-zA-Z0-9+]+/', '', $phone)

The regex will remove a 0 at the start of string with the ^0 alternative, and the [^a-zA-Z0-9+]+ will remove any one or more chars other than ASCII letters, digits and + anywhere else in the string.

See the regex demo.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement