gpt4 book ai didi

javascript - 删除 PHP 中所有 REAL Javascript 注释

转载 作者:行者123 更新时间:2023-11-28 07:18:23 25 4
gpt4 key购买 nike

我正在寻找一种使用 PHP 去除 HTML 代码中所有 javascript 注释的解决方案。

我想仅删除 Javascript 注释(而不是 HTML 注释等)。我认为正则表达式不是一个解决方案,因为它无法理解是否是真正的注释还是字符串的一部分。示例:

<script>

// This is a comment
/* This is another comment */

// The following is not a comment
var src="//google.com";

</script>

有办法吗?非常感谢提前

最佳答案

要做的第一件事:您需要提取脚本标签的内容。为此,请使用 DOMDocument:

$dom = new DOMDocument;
$dom->loadHTML($html);

$scriptNodes = $dom->getElementsByTagName('script');

第二步是删除每个脚本节点的所有 JavaScript 注释。

如果需要,您可以使用第三方 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>])</code> is a [lookahead][3] that checks if the next character is one of these <code>[ ( : , = / " ' </code> 。此测试的目的是防止在字符不同时测试以下交替的每个分支。如果删除它,模式将发挥相同的作用,只是快速跳过字符串中无用的位置。

(*SKIP)是一个回溯控制动词。当该模式在其之后失败时,将不会尝试之前匹配的所有位置。

(*FAIL)也是一个回溯控制动词,强制模式失败。

(?|..(..)..(..)..|..(..)..(..)..)是一个分支重置组。在其中,捕获组在每个分支中分别具有相同的数字(对于此模式为 9 和 10)

关于javascript - 删除 PHP 中所有 REAL Javascript 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30573253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com