Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace repeating characters with exceptions

Tags:

regex

replace

php

How can you translate this into Regex: Replace any char (aka '.') that is repeating more than once and replace it with one of that char with the exception of "ii" and "iii".

$reg = preg_replace('/(.)/1{1,}/','', $string);

Now this must replace VVVVV with V or .... with . and must not replace Criiid (or Criid) but Criiiiiiid with Crid.

Feel free to comment if you don't understand the question.

like image 374
faq Avatar asked Aug 31 '26 13:08

faq


2 Answers

preg_replace('/([^i])\1+|(i){4,}/', '\1\2', $string)

Note that this will squeeze everything -- spaces, newlines, etc.

like image 182
Explosion Pills Avatar answered Sep 02 '26 04:09

Explosion Pills


The first alternative replaces anything but i, the second alternative replaces any is which occur four times or more:

$reg = preg_replace('/([^i])\1{1,}|(i){4,}/','\1\2', $string);

Or (thanks to @Enissay):

$reg = preg_replace('/([^i])\1+|(i){4,}/','\1\2', $string);
like image 33
Reeno Avatar answered Sep 02 '26 03:09

Reeno



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!