PHP remove commas from numeric strings

05/23/2020 21:00:02

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";

    $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.

Verified Answer (23 Votes)

02/18/2012 01:28:07

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


Answer #2 (95 Votes)

02/18/2012 01:29:15

Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;

Answer #3 (20 Votes)

04/07/2015 22:24:39

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.