1

我正在寻找使用正则表达式删除多个换行符。说我有这个文本:

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

然后我想用

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

所以我的要求是:

  1. 它将删除所有多个换行符并将替换为一个换行符
  2. 它将删除所有多个空格并替换为一个空格
  3. 空格也会被修剪

我确实搜索了很多,但找不到解决方案 - 我得到的最接近的是这个Removing冗余换行符与正则表达式

4

3 回答 3

1

用这个 :

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

感谢使用正则表达式删除多余的换行符

于 2012-09-08T05:08:38.283 回答