Mike
Mike

Reputation: 2012

Remove multiple duplicate characters from string

I have strings like this one:

$str = 'This -----is a bbbb test';

How can I remove all duplicate characters if it occurs more than 3 times?

So, for example, the string above must look as follows:

'This is a  test';

Upvotes: 3

Views: 2736

Answers (2)

dan-lee
dan-lee

Reputation: 14502

$t = preg_replace('/(\S)\1{3,}/', '', $t);

Every non-space longer than 3 chars will be replaced with nothing

Upvotes: 1

user142162
user142162

Reputation:

You can do this using regular expressions and preg_replace():

$new_str = preg_replace('/(.)\1{3,}/', '', $str);

Upvotes: 7

Related Questions