Remove non-numeric characters from a string in PHP
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.
|
1 2 3 4 5 6 7 8 9 10 |
<?php $text = '999-999-9999'; $result = preg_replace('/[^0-9]/', '', $text); echo $result; /* Output: 9999999999 */ ?> |
A better option is to use the \D special character, which matches a non-digit character.
|
1 2 3 4 5 6 7 8 9 10 |
<?php $text = '999-999-9999'; $result = preg_replace('/\D/', '', $text); echo $result; /* Output: 9999999999 */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $text = '-99.99$'; $result = filter_var($text, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND); echo $result; /* Output: -99.99 */ ?> |
That’s all about removing non-numeric characters from a string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)