要做的第一件事:你需要提取脚本标签的内容。为此,请使用 DOMDocument:
$dom = new DOMDocument;
$dom->loadHTML($html);
$scriptNodes = $dom->getElementsByTagName('script');
第二步是删除每个脚本节点的所有 javascript cmets。
如果需要,您可以使用第三方 javascript 解析器,但也可以使用正则表达式。您需要做的就是防止将引号之间的部分考虑在内。
为此,您必须搜索引号之间的第一部分并丢弃它们。用 javascript 做到这一点的唯一困难是引号可以在正则表达式模式中,例如:
/pattern " with a quote/
所以你也需要找到模式来防止任何错误。
模式示例:
$pattern = <<<'EOD'
~
(?(DEFINE)
(?<squoted> ' [^'\n\\]*+ (?: \\. [^'\n\\]* )*+ ' )
(?<dquoted> " [^"\n\\]*+ (?: \\. [^"\n\\]* )*+ " )
(?<tquoted> ` [^`\\]*+ (?s: \\. [^`\\]*)*+ ` )
(?<quoted> \g<squoted> | \g<dquoted> | \g<tquoted> )
(?<scomment> // \N* )
(?<mcomment> /\* [^*]*+ (?: \*+ (?!/) [^*]* )*+ \*/ )
(?<comment> \g<scomment> | \g<mcomment> )
(?<pattern> / [^\n/*] [^\n/\\]*+ (?>\\.[^\n/\\]*)* / [gimuy]* )
)
(?=[[(:,=/"'`])
(?|
\g<quoted> (*SKIP)(*FAIL)
|
( [[(:,=] \s* ) (*SKIP) (?: \g<comment> \s* )*+ ( \g<pattern> )
|
( \g<pattern> \s* ) (?: \g<comment> \s* )*+
( \. \s* ) (?:\g<comment> \s* )*+ ([A-Za-z_]\w*)
|
\g<comment>
)
~x
EOD;
然后你替换每个脚本节点的内容:
foreach ($scriptNodes as $scriptNode) {
$scriptNode->nodeValue = preg_replace($pattern, '$9${10}${11}', $scriptNode->nodeValue);
}
$html = $dom->saveHTML();
demo
图案细节:
((?DEFINE)...) 是一个您可以放置稍后需要的所有子模式定义的区域。 “真正的”模式开始于之后。
(?<name>...) 被命名为子模式。它与捕获组相同,只是您可以使用其名称(如\g<name>)而不是其编号来引用它。
*+ 是possessive quantifiers
\N 表示不是换行符的字符
(?=[[(:,=/"'])</code> is a [lookahead][3] that checks if the next character is one of these <code>[ ( : , = / " ' 。此测试的目的是防止在字符不同时测试以下交替的每个分支。如果你删除它,模式将同样工作,只是快速跳过字符串中无用的位置。
(*SKIP) 是一个回溯控制动词。当模式在它之后失败时,将不会尝试在它之前匹配的所有位置。
(*FAIL) 也是一个回溯控制动词,强制模式失败。
(?|..(..)..(..)..|..(..)..(..)..) 是一个分支重置组。在其中,捕获组在每个分支中分别具有相同的数字(此模式为 9 和 10)。