Stripping Everything but Numbers in PHP using RegEx

Here’s a useful little regular expression that will strip everything but numbers from a string in PHP.

preg_replace(“/[^0-9]/”,””,”604-619-5135″);

This uses PHP’s preg_replace function to replace everything but numbers with nothing. I used it to strip the dashes from ZIP+4 codes and also reformat phone numbers without forcing the user to enter it in my preferred format (if possible, it’s always better to clean up user input yourself than yell at the user for not entering it your way).

I gleaned this solution from “Chris” on StackOverflow so all credit goes to him. I recommend using RegExr when building your expression. I’ve covered this in more detail previously.

Leave a Reply