2

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.

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

7 Comments

I believe in PHP's PCRE you can use the branch reset group (?|...|...), so that it becomes preg_replace('/(?|([^i])\1+|(i){4,})/', '\1', $string)
@ExplosionPills what exactly do you mean by squeeze
@ExplosionPills can you also tell me the | which you have used is between \1+ and i{4,} or ([^i])\1+ and (i){4,}
@aelor | is the second thing. Squeeze just means translating repetitions of a character to a single version of that character (think of squeezing in real life)
@ExplosionPills so you can even do ([^i])\1+|(i)\1{4,}
|
3

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);

1 Comment

@Enissay: Thanks :) I just copied the first part from the question so it looks familiar to the poster :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.