Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 746
user1082428 Avatar asked Feb 17 '12 20:02

user1082428


People also ask

How do I remove all commas from a string?

To remove all commas from a string, call the replace() method, passing it a regular expression to match all commas as the first parameter and an empty string as the second parameter. The replace method will return a new string with all of the commas removed.

How do I remove a comma from a number in typescript?

replace(/\,/g,''); // 1125, but a string, so convert it to number a=parseInt(a,10); Hope it helps.

How remove all special characters from a string in PHP?

Using str_ireplace() Method: The str_ireplace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “).


2 Answers

Do it the other way around:

$a = "1,435"; $b = str_replace( ',', '', $a );  if( is_numeric( $b ) ) {     $a = $b; } 
like image 150
JJJ Avatar answered Sep 19 '22 23:09

JJJ


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

like image 27
Kenaniah Avatar answered Sep 18 '22 23:09

Kenaniah