Function to remove all non-numeric characters in PHP

Sometimes it’s helpful to ONLY get numeric characters.
Phone numbers, age — whatever your little PHP heart desires.

function remove_non_numeric($string) {
return preg_replace('/\D/', '', $string)
}

WRAAAAAAA,
Bryan

Related reading

  • No Related Post

13 Responses to “Function to remove all non-numeric characters in PHP”

  1. Paulius  on October 8th, 2009

    Is it worth entire blog post?

  2. bryan  on October 12th, 2009

    Is it worth an entire comment?

  3. wes  on November 12th, 2009

    The answer is yes.

  4. donwilson  on November 13th, 2009

    Is it worth an entire reply?

  5. James  on November 13th, 2009

    Actually, it’s worth it. Thank you for this.

  6. bryan  on November 14th, 2009

    You’re welcome.

  7. wefwef  on November 14th, 2009

    Line 2 is missing a “;”.

    This is more readable I think:

    preg_replace(’/[^0-9]/Uis’, ”, $string);

    Cheers

  8. bear  on December 7th, 2009

    THK 4 this simple but useful.

  9. Fishing  on May 13th, 2010

    Yes it absolutely was. I’m sending out text message notifications for new fishing reports and have to strip non-numeric chars. Thanks!

  10. Mr Incredible  on May 27th, 2010

    It was a rather short post but handy. Imparting any knowledge shouldn’t be criticized.

    Paulius, you wouldn’t be here if you didn’t need to know about it right?

  11. ergec  on January 14th, 2011

    In case you are looking for something to convert amount with currency “$50.5″ to only amount without currency “50.5″

    function convertMoney($string) {
    return preg_replace(’/[^0-9\.]/Uis’, ”, $string);
    }

  12. creatorbri  on March 2nd, 2011

    Is it worth commenting months after the fact?

  13. Eric  on March 4th, 2011

    It’s his blog, jeez.


Leave a Reply