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. 
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.
replace(/\,/g,''); // 1125, but a string, so convert it to number a=parseInt(a,10); Hope it helps.
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 (” “).
Do it the other way around:
$a = "1,435"; $b = str_replace( ',', '', $a );  if( is_numeric( $b ) ) {     $a = $b; } 
                        Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
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