PHP Remove Comma from String or a Number Script


There are some instances where you need to remove comma from a string or a number. For example, you would like PHP to convert 1,234 to 1234 and display to the browser. This where you need to remove commas…

Specifically, for computational purposes, PHP won’t include in the computation for numbers including a comma so you will need to remove it.

This type of application needs to use a PHP function called str_replace:

<?php
//check if post is submitted
if (!$_POST['submit']) {
//form not submitted show form
//entry field
echo '<form action="'.$SERVER['PHP_SELF'].'" method="post">';
echo 'Enter a string or a number containing commas, example 15,020: ';
echo '<input type="text" name="entry" size="20">';
echo '<br />';
echo '<input type="submit" name="submit" value="Submit">';
echo '</form>';
}
else {
//form submitted get data
$entry=trim($_POST['entry']);
//replace comma with space
$entry = str_replace(",", "",$entry);
//echo to the browser
echo '<br />'.$entry;
}
?>

In script above, it asks the user to input any string or number containing a comma, and then the PHP function first remove unnecessary spaces in the string using the trim command.


The PHP function str_replace:

$entry = str_replace(",", "",$entry);

The job is to detect any presence of commas in the variable, and then once it is detected, it will simply be removed. You can modify the above script to suit your own PHP application.



Related posts: