Search code examples
phpstringreplacenumbers

PHP remove commas from numeric strings


In PHP, I have an array of variables that are ALL strings. Some of the values stored are numeric strings with commas.

What I need:

A way to trim the commas from strings, and ONLY do this for numeric strings. This isn't as straightforward as it looks. The main reason is that the following fails:

$a = "1,435";

if(is_numeric($a))
    $a = str_replace(',', '', $a);

This fails because $a = "1435" is numeric. But $a = "1,435" is not numeric. Because some of the strings I get will be regular sentences with commas, I can't run a string replace on every string.


Solution

  • Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)