facebook icon twitter icon angle down linkedin icon youtube icon
Home > Blog > remove-comma-using-php

How to remove comma from string using PHP

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.

Tarikul islam

About Torikul islam

Torikul islam is a professional web developer and affiliate marketer. Join Torikul to learn how to start a website and operate it well. He started his Web Developement career from Bangladesh Association of Software and Information (BASIS) in 2015. Later he continiued his journey to expanding knowledge and sharing it with others.

Write a Comment

No comment yet