删除PHP中所有真实的Javascript注释

Remove all REAL Javascript comments in PHP

本文关键字:Javascript 注释 真实 PHP 删除      更新时间:2023-09-26

我正在寻找一个解决方案,以剥离所有javascript注释在HTML代码中使用PHP。

我想剥离仅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做到这一点的唯一困难是引号可以在regex模式中,例如:
/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();

模式细节:

((?DEFINE)...)是您可以放置稍后需要的所有子模式定义的区域。"真正"

(?<name>...)为子模式。它与捕获组相同,只是您可以使用其名称(如'g<name>)而不是其编号来引用它。

*+是所有格量词

'N表示不是换行符的字符

(?=[[(:,=/"'])</code> is a [lookahead][3] that checks if the next character is one of these <code>[ ( : , = / " ' 。此测试的目的是防止在字符不同的情况下测试以下更改的每个分支。如果您删除它,模式将以相同的方式工作,它只是快速跳过字符串中无用的位置。

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

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

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

使用此函数

function removeComments(str) {
    str = ('__' + str + '__').split('');
    var mode = {
        singleQuote: false,
        doubleQuote: false,
        regex: false,
        blockComment: false,
        lineComment: false,
        condComp: false 
    };
    for (var i = 0, l = str.length; i < l; i++) {
 
        if (mode.regex) {
            if (str[i] === '/' && str[i-1] !== ''') {
                mode.regex = false;
            }
            continue;
        }
 
        if (mode.singleQuote) {
            if (str[i] === "'" && str[i-1] !== ''') {
                mode.singleQuote = false;
            }
            continue;
        }
 
        if (mode.doubleQuote) {
            if (str[i] === '"' && str[i-1] !== ''') {
                mode.doubleQuote = false;
            }
            continue;
        }
 
        if (mode.blockComment) {
            if (str[i] === '*' && str[i+1] === '/') {
                str[i+1] = '';
                mode.blockComment = false;
            }
            str[i] = '';
            continue;
        }
 
        if (mode.lineComment) {
            if (str[i+1] === 'n' || str[i+1] === 'r') {
                mode.lineComment = false;
            }
            str[i] = '';
            continue;
        }
 
        if (mode.condComp) {
            if (str[i-2] === '@' && str[i-1] === '*' && str[i] === '/') {
                mode.condComp = false;
            }
            continue;
        }
 
        mode.doubleQuote = str[i] === '"';
        mode.singleQuote = str[i] === "'";
 
        if (str[i] === '/') {
 
            if (str[i+1] === '*' && str[i+2] === '@') {
                mode.condComp = true;
                continue;
            }
            if (str[i+1] === '*') {
                str[i] = '';
                mode.blockComment = true;
                continue;
            }
            if (str[i+1] === '/') {
                str[i] = '';
                mode.lineComment = true;
                continue;
            }
            mode.regex = true;
 
        }
 
    }
    return str.join('').slice(2, -2);
}

使用这两个链接http://trinithis.awardspace.com/commentStripper/stripper.html

http://james.padolsey.com/javascript/removing-comments-in-javascript/

进一步引用检查它Javascript注释剥离器

这个RegExp将适用于您的示例:

^'/(?:'/|'*).*
PHP代码:

$re = "/^''/(?:''/|''*).*/m"; 
$str = "<script>'n'n// This is a comment'n/* This is another comment */'n'n// The following is not a comment'nvar src='"//google.com'"; 'n'n</script>"; 
preg_match_all($re, $str, $matches);

演示

或者可以这样,来验证*/:

^'/{2}.*|'/'*.*'*'/$
PHP代码:

$re = "/^''/{2}.*|''/''*.*''*''/$/m"; 
$str = "<script>'n'n// This is a comment'n/* This is another comment */'n'n// The following is not a comment'nvar src='"//google.com'"; 'n'n</script>"; 
preg_match_all($re, $str, $matches);

以及接下来