Remove comma from a string in PHP?

In PHP, you can remove commas from a string using the str_replace() function. This function searches for a specific character or substring and replaces it with another value or removes it entirely.

Syntax

str_replace(search, replace, subject)

Parameters:

  • search − The character or string to find (comma in our case)
  • replace − What to replace it with (empty string to remove)
  • subject − The original string to process

Example

Let's remove commas from a string containing a person's name ?

<?php
$name = "John,Smith";
$result = str_replace(',', '', $name);

echo "The actual value is = " . $name . "<br>";
echo "After removing the comma(,) = " . $result . "<br>";
?>
The actual value is = John,Smith
After removing the comma(,) = JohnSmith

Multiple Comma Removal

The str_replace() function removes all occurrences of the comma ?

<?php
$text = "apple,banana,cherry,date";
$cleanText = str_replace(',', '', $text);

echo "Original: " . $text . "<br>";
echo "Cleaned: " . $cleanText . "<br>";
?>
Original: apple,banana,cherry,date
Cleaned: applebananacherrydate

Replace Comma with Space

You can also replace commas with spaces or other characters ?

<?php
$numbers = "1,2,3,4,5";
$spaced = str_replace(',', ' ', $numbers);

echo "With commas: " . $numbers . "<br>";
echo "With spaces: " . $spaced . "<br>";
?>
With commas: 1,2,3,4,5
With spaces: 1 2 3 4 5

Conclusion

The str_replace() function is the most efficient way to remove commas from strings in PHP. It processes all occurrences in a single operation and can replace commas with any desired character or remove them completely.

Updated on: 2026-03-15T09:34:11+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements