Removing multiple duplicate characters from a string

I have lines like this:

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

How to remove all duplicate characters if this happens more than three times?

So, for example, the line above should look like this:

'This is a  test';
+3
source share
2 answers

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

$new_str = preg_replace('/(.)\1{3,}/', '', $str);
+7
source
$t = preg_replace('/(\S)\1{3,}/', '', $t);

Each non-space longer than 3 characters will be replaced by nothing

+1
source

All Articles