Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all duplicate characters in a string?

Tags:

php

Say I have the following:

$str = "1AAABBCCCDDDDDDD";

How can I remove all the duplicate characters in the string? So it would look like this?

$result = "1ABCD";
like image 530
rotaercz Avatar asked Aug 19 '13 02:08

rotaercz


1 Answers

All you need is count_chars():

$result = count_chars( $str, 3);

With the second parameter $mode set to 3, count_chars() will output:

a string containing all unique characters

You can see from this demo that this produces:

1ABCD
like image 196
nickb Avatar answered Oct 22 '22 21:10

nickb