0

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?

  • Instead of removing duplicate can you just find unique? I think the answer here might help https://stackoverflow.com/questions/15391395/php-find-number-of-different-letters-in-a-string – Funk Doc Jan 25 '19 at 18:02
  • 1
    Possible duplicate of [Remove duplicates of certain characters from string](https://stackoverflow.com/questions/9350851/remove-duplicates-of-certain-characters-from-string) – miken32 Jan 25 '19 at 20:06

2 Answers2

1

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))));
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
  • 1
    Your solution works only with 1-byte character sets (default ASCII will work for English & Spanish alphabets only). – user1597430 Jan 25 '19 at 18:03
0

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);
}
user1597430
  • 1,138
  • 1
  • 7
  • 14