0

Why the following won't work?

<?php
 $text = 'Hell   looo   w  orlldddddd!!!!!!!!!';
 $sanitized = preg_replace("/(\w|\s)\1{1,}/mi","$1",$text);
 echo $sanitized;
 ?>

The output expected should be : Hel lo w orld!

Thank you

5
  • 2
    What output did you get? Commented Dec 20, 2012 at 16:53
  • While JavaScript it's still the same regex - possible duplicate of JavaScript RegEx Remove Duplicate Characters Commented Dec 20, 2012 at 16:56
  • same with the original text Commented Dec 20, 2012 at 16:58
  • @JasonMcCreary the answers there don't work like the OP wants. Commented Dec 20, 2012 at 17:03
  • 1
    Best I can do is Helo w orld!. There is ambiguity for the space after w, since it's w o, why should the white space be removed altogether in the case of w o, but not in the case of o w? Commented Dec 20, 2012 at 17:07

2 Answers 2

1

Try this:

$text = 'Hell   looo   w  orlldddddd!!!!!!!!!';
$sanitized = preg_replace('/(\w|\s|.)\\1+/', '$1',$text);
 echo $sanitized;

Outputs:

Hel lo w orld!

This is the best you can do with the regex in this case.

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

17 Comments

Expected output is Helo world!
That is the bast he can ever get. I do not how to explain the regex to remove spaces bitween Hel and lo and not to remove them bitween lo and w
Hell lo -> Helo can be explained with l being the same character after whitespace. But yes, in the end, you can't really get Helo world!, but you can do better than Hel lo w orld!
Oh, lets wait and see what he will say.. You should better provide your answer if you know how to do that..
Regexes are awesome... but they ain't magic! :)
|
-1

You forgot the slash inside the regex:

/(\w|\s)/\1{1,}/mi

3 Comments

/(\w|\s)/\1{1,}/mi - Did you test it? I did. Not working!
I didn't test it, I just found typo in regex. It should have 3 slashes, and \1 can be placed only in second group.
@alex not true, it's usable even in the first one to repeat already found groups: echo preg_replace('/([:])\1+/', '$1', 'a:b::c'); outputs a:b:c

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.