This article demonstrates how to remove non-numeric characters from a string in PHP.

1. Using preg_replace() function

A simple solution is to use preg_replace() function to remove non-numeric characters from a string. This function needs a regular expression to search and replace within a string.

The following solution uses the [^0-9] regex to match non-numeric characters. Note that this regex also removes +, -, ., ,, e, and E from the string.

Download  Run Code

 
A better option is to use the \D special character, which matches a non-digit character.

Download  Run Code

2. Using filter_var() function

Alternatively, you can use the filter_var() function to remove non-numeric characters from the string. The FILTER_SANITIZE_NUMBER_FLOAT sanitization filter removes all characters from the string except digits, +, and -. Note that this also removes the decimal character (.), comma separator (,), and scientific notation (e or E) from the string, unless you specify FILTER_FLAG_ALLOW_FRACTION, FILTER_FLAG_ALLOW_THOUSAND, and FILTER_FLAG_ALLOW_SCIENTIFIC flags, respectively.

Download  Run Code

That’s all about removing non-numeric characters from a string in PHP.