Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove unwanted commas from a string?

Tags:

php

How can i remove duplicate commas used in string.

String = ",a,b,c,,,d,,"

I tried rtrim and itrim functions and removed the unwanted commas from beginning and ending .How can i remove duplicate commas ?

like image 727
Rahul R Avatar asked Jun 07 '13 11:06

Rahul R


3 Answers

Try this:

$str = preg_replace('/,{2,}/', ',', trim($str, ','));

The trim will remove starting and trailing commas, while the preg_replace will remove duplicate ones.

See it in action!

Also, as @Spudley suggested, the regex /,{2,}/ could be replaced with /,,+/ and it would work too.

EDIT:

If there are spaces between commas, you may try adding the following line after the one above:

$str = implode(',', array_map('trim', explode(',', $str)))
like image 85
Matteo Tassinari Avatar answered Oct 08 '22 15:10

Matteo Tassinari


i think you can just explode your string and then create a new one getting only relevant data

$string = ",a,b,c,,,d,,";
$str = explode(",", $string);
$string_new = '';
foreach($str as $data)
{
    if(!empty($data))
    {
        $string_new .= $data. ',';
    }
}
echo substr_replace($string_new, '', -1);

This will output

a,b,c,d

Live Demo

EDITED

If you are having problems with blank spaces you can try use this code

$string = ",a,b,c, ,,d,,";

$str = explode(",", str_replace(' ', '', $string));
$string_new = '';
foreach($str as $data)
{
    if(!empty($data))
    {
        $string_new .= $data. ',';
    }
}
echo substr_replace($string_new, '', -1);

This should solve spaces issue

like image 31
Fabio Avatar answered Oct 08 '22 15:10

Fabio


Probably not very fast, but a simple method may be:

$str = "a,b,c,,,d";
$str2 = "";
while($str <> $str2) {
    $str2 = $str;
    $str = str_replace(',,', ',', $str);
}
like image 31
neelsg Avatar answered Oct 08 '22 16:10

neelsg