1

Input: "abbbcdaa" Output: "abcd"

With the follow regex the out put is abcda

preg_replace('/(.)\\1*/', '$1', "abbbcdaa");

how to get abcd using pre_replace

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Aditya Joshi
  • 245
  • 4
  • 12

1 Answers1

0

This should do it:

$string="abbbcdaa";
echo preg_replace('/(.)(?=.*?\1)/','',$string);

The above outputs:

bcda

Alternatively, you can use:

echo count_chars($string,3);

That would also return unique characters abcd.

Good luck!

angelcool.net
  • 2,505
  • 1
  • 24
  • 26
  • Can you explain this part of regex (?=.*?\1) – Aditya Joshi Nov 08 '15 at 08:43
  • That's a look-ahead (google look-arounds). The entire regex will delete a char from the input string only if that char appears again later in the string. Also, take a look here: http://stackoverflow.com/questions/2582940/how-do-i-remove-duplicate-characters-and-keep-the-unique-one-only-in-perl – angelcool.net Nov 08 '15 at 17:11