PHP How to set the preg-groups to “non-capture” (?:…)

倾然丶 夕夏残阳落幕 提交于 2019-12-12 09:18:23

问题


In HTML page, I remove HTML comments like this

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

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

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?


回答1:


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.

Details:

  • <!-- - start of comment
  • [^-]* - 0+ non--
  • (?:-(?!->)[^-]*)* - 0+ sequences of - that is not followed with -> and then 0+ non--s
  • --> - comment end


来源:https://stackoverflow.com/questions/36885622/php-how-to-set-the-preg-groups-to-non-capture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!