Mim
Mim

Reputation: 37

How to remove duplicate letters in string in PHP

So I have this:

array(2) { [0]=> string(2) "cd" [1]=> string(6) "feegeg" }

And I have this code:

foreach ($elem as $key => $value) {
    echo preg_replace('{(.)\1+}','$1',$value);
} 

Which outputs:

cdfegeg

But I need it to output:

cdfeg

What do I need with preg_replace() or maybe not using preg_replace(), so I can get this output?

Upvotes: 0

Views: 1277

Answers (2)

user1597430
user1597430

Reputation: 1146

Multibyte character sets solution:

$buffer = [];

foreach (['cd', 'feegeg'] as $string)
{
    $chars = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);

    foreach ($chars as $index => $char)
    {
        if (isset($buffer[$char]))
        {
            unset($chars[$index]);
        }

        $buffer[$char] = true;
    }

    echo implode('', $chars);
}

Upvotes: 0

Alex Howansky
Alex Howansky

Reputation: 53646

I tend to avoid regex when possible. Here, I'd just split all the letters into one big array and then use array_unique() to de-duplicate:

$unique = array_unique(str_split(implode('', $elem)));

That gives you an array of the unique characters, one character per array element. If you'd prefer those as a string, just implode the array:

$unique = implode('', array_unique(str_split(implode('', $elem))));

Upvotes: 1

Related Questions