1

我需要清理即使在单词中也添加了无效换行符的文本,以及在单词之间添加有效换行符的文本,因此存在前导或训练空间。

使用 php 尝试从由字符包围的多行文本中删除这些换行符,这意味着之前或之后没有空格。

$textbefore = "text has newlines in wo\nrds and normal newlines \n bewtween words and again in wo\nrds";
$textafter = "text has newlines in words and normal newlines \n bewtween words and again in words";

试过这个

$pattern="/(.{2}\n.{1})/m";

我已经尝试了所有可能的模式,但在最好的情况下,只有第一次出现是匹配的。

任何想法都受到高度赞赏。

4

2 回答 2

2

您可以将其简化为以下正则表达式:

$textafter = preg_replace( "/(?<=\S)\n|\n(?=\S)/", '', $textbefore);

其中指出它必须找到:

  1. (?<=\S)\n- 前面有非空格字符的换行符,或
  2. \n(?=\S)- 后跟非空格字符的换行符

当它找到这些换行符中的任何一个时,它将用任何内容(空字符串)替换它们。

您可以从这个演示中看到,这会产生字符串:

string(82) "text has newlines in words and normal newlines 
 bewtween words and again in words"
于 2013-09-20T14:44:09.663 回答
0

您可以使用负前瞻和负后瞻:

/(?<!\s)\n(?!\s)/

它将匹配前后没有空格的新行

现场演示

于 2013-09-20T15:29:13.880 回答