w3resource

PHP String Exercises : Remove comma(s) from the specified numeric string


25. Remove Commas from Numeric String

Write a PHP script to remove comma(s) from the following numeric string.

Sample String : '2,543.12'

Visual Presentation:

PHP String Exercises: Remove comma(s) from the specified numeric string

Sample Solution:

PHP Code:

<?php
$str1 = "2,543.12";
// Define the original string.

$x = str_replace( ',', '', $str1);
// Remove all commas from the original string.

if( is_numeric($x))
// Check if the resulting string is numeric.
{
  echo $x."\n";
  // If numeric, echo the modified string.
}
?>

Sample Output:

2543.12 

Explanation:

The above PHP code snippet removes all commas from the string "2,543.12" using the str_replace() function.

  • str_replace(',', '', $str1) removes all occurrences of the comma , from the original string $str1, resulting in the string '2543.12'.
  • The is_numeric() function checks if the resulting string $x is numeric.
  • If $x is numeric, it echoes out the modified string '2543.12'.

So, the output of this code would be 2543.12.

Flowchart :

Flowchart: Remove comma(s) from the specified numeric string

For more Practice: Solve these Related Problems:

  • Write a PHP script to remove all commas from a numeric string and convert the result to a floating-point number.
  • Write a PHP function to clean a monetary string by eliminating commas and then format it with number_format().
  • Write a PHP program to use str_replace() to strip commas from a price string before performing arithmetic operations.
  • Write a PHP script to parse a numeric string with commas and output the number without the commas using regex.

Go to:


PREV : Select First Five Words from a String.
NEXT : Print Letters from 'a' to 'z'.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.