How to remove comma from string using PHP
Last Updated on Dec 13, 2022 - Written By Torikul Islam
You can use str_replace() function to remove comma from a string. str_replace() is a PHP built-in function.
Similarly str_replace() function, you can use preg_replace() function to eliminate comma. But this approach is bit complex compare to former one.
Basic syntax
str_replace('substring', 'replaced_string', 'original_string');
Or
preg_replace('substring', 'replaced_string', 'original_string');
We need to provide three parameters for both methods.
1. Substring is the first parameter which should be replaced with replaced_string.
2. Replaced_string will replace the substring.
3. Original_string will contain the full string from where you want to remove comma.
In the placement of parameters, you can use PHP variables.
Discussion and examples
Example 1: By using str_replace() function
<?php
//input string
$string = 'This is my example string, i want to remove comma from here, and I am using str replace function.';
//removing all comma
$strings = str_replace( ',', '', $string );
//showing result
echo $string;
?>
Output:
This is my example string i want to remove comma from here and I am using str replace function.
Example 2: By using preg_replace() function
<?php
//input string
$string = 'This is my example string, i want to remove comma from here, and I am using preg replace function.';
//removing all comma using regex
$string = preg_replace('/[,]/','',$string);
//showing result
echo $string;
?>
Output:
This is my example string i want to remove comma from here and I am using preg replace function.
Both str_replace() and preg_replace() work almost similarly, but first one can works only for fixed value, while second one has more flexible application.