【问题标题】:PHP RegExp: Capture all HTML closing tags followed by new line characterPHP RegEx:捕获所有 HTML 结束标记,后跟换行符
【发布时间】:2016-03-24 18:27:39
【问题描述】:

我想捕获后跟换行符的任何 HTML 结束标记,并仅用 HTML 标记替换它们。

比如我想转这个:

<ul>\n
    <li>element</li>\n
</ul>\n\n
<br/>\n\n
Some text\n

进入这个:

<ul>
    <li>element</li>
</ul>\n
<br/>\n
Some text\n

问题是我无法使用正则表达式捕获\n 字符:

preg_match_all('/(<\/[a-zA-Z]*>|<[a-zA-Z]*\/>)\n/s', $in, $matches);

一旦我将 \n 放在我的模式中的某个位置,matches 数组将返回空值。

有趣的是,如果我尝试单独匹配 \n 字符,它会找到所有字符:

preg_match_all('/\n/s', $in, $matches);

【问题讨论】:

  • 所以你想用\n替换\n\n?单独匹配不会取代任何东西。

标签: php regex


【解决方案1】:

试试:

preg_match_all('/(<\/[a-zA-Z]*>|<[a-zA-Z]*\/>)\\n/s', $in, $matches);

你必须转义“\”字符。

【讨论】:

    【解决方案2】:

    你可以使用类似下面的东西:

    (<[^>]+>)$\R{2}
    # capture anything between a pair of < and > at the end of the line
    # followed by two newline characters
    

    您需要使用multiline 模式,请参阅a demo on regex101.com
    PHP 中,这将是:

    $regex = '~(<[^>]+>)$\R{2}~m';
    $string = preg_replace($regex, "$1", $your_string_here);
    

    通常,DomDocument 解析器提供了保留或丢弃空格的可能性,因此您最好使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      • 2016-11-24
      • 1970-01-01
      相关资源
      最近更新 更多