Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple duplicate characters from string

Tags:

string

php

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';
like image 373
Mike Avatar asked Nov 20 '25 03:11

Mike


2 Answers

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

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

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

like image 37
dan-lee Avatar answered Nov 21 '25 16:11

dan-lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!