Search code examples
phpregexduplicatespreg-replacenon-alphanumeric

How clear duplicate consecutive non-alphabetic characters in a string?


Matching the string only for: ,.:- how I can remove duplicate values from a string? For example having:

"ab::::c ---------d,,,e ..........f ::a-b,,,c..d"

Expected output:

"ab:c -d,e .f :a-b,c.d" 

Solution

  • Here we are using preg_replace to achieve desired output.

    Regex: ([,.:-])\1+ Regex demo

    Or

    Regex: (,|\.|:|-)\1+Regex demo

    1. This will match a character and add that in captured group

    2. using that captured group for \1 more than one occurence.

    Replacement: $1

    Try this code snippet here

    <?php
    ini_set('display_errors', 1);
    
    $string="ab::::c ---------d,,,e ..........f ::a-b,,,c..d";
    echo preg_replace('/([,.:-])\1+/', '$1', $string);
    

    Solution 2: using foreach loop

    Try this code snippet here

    $string="aab::::css ---------ddd,,,esddsff ..........f ::a-b,,,c..d";
    $chars=  str_split($string);
    $result=array();
    foreach($chars as $character)
    {
        if($character!=end($result) ||  !in_array($character, array(":",",",".","-")))
        {
            $result[]=$character;
        }
    }
    print_r(implode("",$result));