In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.
Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
Strip all characters but letters, numbers, and whitespace Finally, if you want to strip all characters from your string other than letters, numbers, and whitespace, this regular expression will do the trick: $res = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
You could use preg_replace to swap out all non-numeric characters and the comma and period/full stop as follows:
$testString = '12.322,11T';
echo preg_replace('/[^0-9,.]+/', '', $testString);
The pattern can also be expressed as /[^\d,.]+/
I'm surprised there's been no mention of filter_var here for this being such an old question...
PHP has a built in method of doing this using sanitization filters. Specifically, the one to use in this situation is FILTER_SANITIZE_NUMBER_FLOAT
with the FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND
flags. Like so:
$numeric_filtered = filter_var("AR3,373.31", FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
echo $numeric_filtered; // Will print "3,373.31"
It might also be worthwhile to note that because it's built-in to PHP, it's slightly faster than using regex with PHP's current libraries (albeit literally in nanoseconds).
Simplest way to truly remove all non-numeric characters:
echo preg_replace('/\D/', '', $string);
\D
represents "any character that is not a decimal digit"
http://php.net/manual/en/regexp.reference.escape.php
You could use filter_var
to remove all illegal characters except digits, dot and the comma.
FILTER_SANITIZE_NUMBER_FLOAT
filter is used to remove all non-numeric character from the string.FILTER_FLAG_ALLOW_FRACTION
is allowing fraction separator " . "
FILTER_FLAG_ALLOW_THOUSAND
to get comma from the string.Code
$var1 = '12.322,11T';
echo filter_var($var1, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
Output
12.322,11
To read more about filter_var() and Sanitize filters
If letters are always in the beginning or at the end, you can simply just use trim...no regex needed
$string = trim($string, "a..zA..Z"); // this also take care of lowercase
"AR3,373.31" --> "3,373.31"
"12.322,11T" --> "12.322,11"
"12.322,11" --> "12.322,11"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With