Home > Back-end >  How to remove consecutive duplicate commas from a php string
How to remove consecutive duplicate commas from a php string

Time:12-06

How to remove consecutive duplicate commas in php. Tried this piece of code. It works when there is no space before comma.

<?php
$a="test, , 1, , , 245 Park Avenue, New York, NY";
$my_string = preg_replace("/, /", ",", $a);
$string=trim($my_string);
echo $string;
?>

expeted output:

$a="test, 1, 245 Park Avenue, New York, NY";

CodePudding user response:

This can be accomplished with array_map, array_filter and implode:

<?php

$a = "test, , 1, , , 245 Park Avenue, New York, NY";

$explode = array_map(function ($e) {
    return trim($e);
}, explode(',', $a));

$filter = array_filter($explode);
$string = implode(', ', $filter);

echo $string . PHP_EOL;

Returns test, 1, 245 Park Avenue, New York, NY

CodePudding user response:

Change your regular expression to this: (?:,\s*){2,}

You can test it here: https://regex101.com/r/1vFhVb/1/

Details

  • ,\s* means a comma followed by some spaces or not (includes tabs too).

  • (?:) is just a non-capturing group because we want ,\s* several times so we put it in a non-capturing group like this (?:,\s*) and then we can add the {2,} to say we want this 2 or more times.

We then replace it by , (I added the space for readability).

$re = '/(?:,\s*){2,}/m';
$str = 'test, , 1, , , 245 Park Avenue, New York, NY';
$subst = ', ';

$result = preg_replace($re, $subst, $str);

echo $result;

displays: test, 1, 245 Park Avenue, New York, NY

CodePudding user response:

You can use str_replace or explode and implode.

If you have a string like $a, then you can simply use str_replace.

$a="test, , 1, , , 245 Park Avenue, New York, NY";
$my_string = str_replace(" ,","",$a);
$string=trim($my_string);

But if you have a string like $b, you have to use implode and explode to construct the new string. (Note the commas without leading spaces)

$b = "test, , 1, , ,,, 245 Park Avenue, New York, NY";

$strArray = explode(',', $b);

$myArray = [];
foreach ($strArray as $str){

    if (trim($str) != null || trim($str) != ""){
        $myArray[] = $str;
    }

}

$myStr = implode(',', $myArray);
  • Related