【问题标题】:php regex - remove only newlines which do not have space before or afterphp regex - 仅删除前后没有空格的换行符
【发布时间】:2013-09-20 14:35:17
【问题描述】:

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

使用 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";

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

高度赞赏任何想法。

【问题讨论】:

  • 稍微颠倒一下这个问题,如果换行符在两边都被文本包围,它是否只有“无效”?如果它在字符串的开头或结尾呢?
  • 我认为您假设正则表达式了解语言。由你来定义一个“词”。直观地注意到一种语言模式并不一定意味着它可以被翻译成正则表达式,尤其是在涉及“单词”时。

标签: php regex newline


【解决方案1】:

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

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

这说明它必须找到:

  1. (?&lt;=\S)\n - 前面有非空格字符的换行符,或者
  2. \n(?=\S) - 后跟一个非空格字符的换行符

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

this demo 可以看出,这会产生字符串:

string(82) "text has newlines in words and normal newlines 
 bewtween words and again in words"

【讨论】:

    【解决方案2】:

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

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

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

    Live Demo

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2011-06-21
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      相关资源
      最近更新 更多