1

I am looking to remove multiple line breaks using regular expression. Say I have this text:

"On the Insert tab\n \n\nthe galleries include \n\n items that are designed"

then I want to replace it with

"On the Insert tab\nthe galleries include\nitems that are designed"

So my requirement is:

  1. it will remove all multiple newlines and will replace with one newline
  2. It will remove all multiple spaces and will replace with one space
  3. Spaces will be trimmed as well

I do searched a lot but couldn't find solution - the closest I got was this one Removing redundant line breaks with regular expressions.

4

3 に答える 3

1

Use this :

echo trim(preg_replace('#(\s)+#',"$1",$string));
于 2012-09-07T10:11:13.467 に答える
0
$text = str_replace("\r\n", "\n", $text); // converts Windows new lines to Linux ones
while (strpos($text, "\n\n") != false)
    {
        $text = str_replace("\n\n", "\n", $text);
    }

That will sort out newline characters.

于 2012-09-07T10:27:33.240 に答える
0
$text = trim($text);
preg_replace('/\s+/', ' ', $text);
preg_replace('/(?:\s*(?:\r\n|\r|\n)\s*){2}/s', "\n", $text);

Thanks to Removing redundant line breaks with regular expressions

于 2012-09-08T05:08:38.283 に答える