Rahul R
Rahul R

Reputation: 207

How to remove unwanted commas from a string?

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 ?

Upvotes: 6

Views: 1129

Answers (4)

Subrata Mallik
Subrata Mallik

Reputation: 1

<?php
$str = ",a,b,c,,,d,,"
echo $str=str_replace(',,','',$str);
?>

Output: ,a,b,c,d


<?php 
$str = ",a,b,c,,,d,,"
echo $str=trim(str_replace(',,','',$str),',');
?>

Output: a,b,c,d

Upvotes: 0

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

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)))

Upvotes: 14

Fabio
Fabio

Reputation: 23490

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

Upvotes: 4

neelsg
neelsg

Reputation: 4842

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);
}

Upvotes: 2

Related Questions