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.


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

This site uses Akismet to reduce spam. Learn how your comment data is processed.