PHP如何将preg-groups设置为“non-capture”(?:...)

时间:2022-04-08 16:48:53

In HTML page, I remove HTML comments like this

在HTML页面中,我删除了这样的HTML注释

$contentHTML = preg_replace("#(?=<!--)([\s\S]*?)-->#", "", $contentHTML);

But on a huge page for preg_replace, I got "PHP Fatal error: Allowed memory size ..."

但是在preg_replace的大页面上,我得到了“PHP致命错误:允许的内存大小......”

Perhaps, one solution, would use the non-matching group to avoid capturing text? Could someone explain how use on-matching group ?:

或许,一种解决方案是使用非匹配组来避免捕获文本?有人可以解释如何使用匹配组吗?:

Or how can I suppress HTML comments in huge page without preg_replace?

或者如何在没有preg_replace的情况下在大页面中抑制HTML注释?

1 个解决方案

#1


2  

Just unroll the regex as

只需将正则表达式展开为

$contentHTML = preg_replace("#<!--[^-]*(?:-(?!->)[^-]*)*-->#", "", $contentHTML);

See the regex demo. Comapre with yours taking about 3 times as more steps as mine with a very short example.

请参阅正则表达式演示。与你的Comapre相比,你的步数大约是我的3倍,只有很短的例子。

Details:

  • <!-- - start of comment
  • [^-]* - 0+ non--
  • [^ - ] * - 0+非 -

  • (?:-(?!->)[^-]*)* - 0+ sequences of - that is not followed with -> and then 0+ non--s
  • (?: - (?! - >)[^ - ] *)* - 0+序列 - 未跟随 - >然后0+非 - s

  • --> - comment end
  • - > - 评论结束

#1


2  

Just unroll the regex as

只需将正则表达式展开为

$contentHTML = preg_replace("#<!--[^-]*(?:-(?!->)[^-]*)*-->#", "", $contentHTML);

See the regex demo. Comapre with yours taking about 3 times as more steps as mine with a very short example.

请参阅正则表达式演示。与你的Comapre相比,你的步数大约是我的3倍,只有很短的例子。

Details:

  • <!-- - start of comment
  • [^-]* - 0+ non--
  • [^ - ] * - 0+非 -

  • (?:-(?!->)[^-]*)* - 0+ sequences of - that is not followed with -> and then 0+ non--s
  • (?: - (?! - >)[^ - ] *)* - 0+序列 - 未跟随 - >然后0+非 - s

  • --> - comment end
  • - > - 评论结束