繁体   English   中英

从 PHP 代码中自动删除注释的最佳方法

[英]Best way to automatically remove comments from PHP code

从 PHP 文件中删除注释的最佳方法是什么?

我想做一些类似于 strip-whitespace() 的事情 - 但它也不应该删除换行符。

例如:

我要这个:

<?PHP
// something
if ($whatsit) {
    do_something(); # we do something here
    echo '<html>Some embedded HTML</html>';
}
/* another long 
comment
*/
some_more_code();
?>

成为:

<?PHP
if ($whatsit) {
    do_something();
    echo '<html>Some embedded HTML</html>';
}
some_more_code();
?>

(虽然如果空行保留在注释被删除的地方,那是不行的)。

这可能是不可能的,因为需要保留嵌入的 html - 这就是谷歌上出现的问题。

我会使用tokenizer 这是我的解决方案。 它应该适用于 PHP 4 和 5:

$fileStr = file_get_contents('path/to/file');
$newStr  = '';

$commentTokens = array(T_COMMENT);
    
if (defined('T_DOC_COMMENT')) {
    $commentTokens[] = T_DOC_COMMENT; // PHP 5
}

if (defined('T_ML_COMMENT')) {
    $commentTokens[] = T_ML_COMMENT;  // PHP 4
}

$tokens = token_get_all($fileStr);

foreach ($tokens as $token) {    
    if (is_array($token)) {
        if (in_array($token[0], $commentTokens)) {
            continue;
        }
        
        $token = $token[1];
    }

    $newStr .= $token;
}

echo $newStr;

如何使用 php -w 生成一个去掉注释和空格的文件,然后使用像PHP_Beautifier这样的美化重新格式化以提高可读性?

$fileStr = file_get_contents('file.php');
foreach (token_get_all($fileStr) as $token ) {
    if ($token[0] != T_COMMENT) {
        continue;
    }
    $fileStr = str_replace($token[1], '', $fileStr);
}

echo $fileStr;

编辑我意识到 Ionut G. Stan 已经提出了这个建议,但我会在这里留下这个例子

这是上面发布的函数,修改为递归删除目录及其所有子目录中的所有 php 文件中的所有注释:

function rmcomments($id) {
    if (file_exists($id)) {
        if (is_dir($id)) {
            $handle = opendir($id);
            while($file = readdir($handle)) {
                if (($file != ".") && ($file != "..")) {
                    rmcomments($id."/".$file); }}
            closedir($handle); }
        else if ((is_file($id)) && (end(explode('.', $id)) == "php")) {
            if (!is_writable($id)) { chmod($id,0777); }
            if (is_writable($id)) {
                $fileStr = file_get_contents($id);
                $newStr  = '';
                $commentTokens = array(T_COMMENT);
                if (defined('T_DOC_COMMENT')) { $commentTokens[] = T_DOC_COMMENT; }
                if (defined('T_ML_COMMENT')) { $commentTokens[] = T_ML_COMMENT; }
                $tokens = token_get_all($fileStr);
                foreach ($tokens as $token) {    
                    if (is_array($token)) {
                        if (in_array($token[0], $commentTokens)) { continue; }
                        $token = $token[1]; }
                    $newStr .= $token; }
                if (!file_put_contents($id,$newStr)) {
                    $open = fopen($id,"w");
                    fwrite($open,$newStr);
                    fclose($open); }}}}}

rmcomments("path/to/directory");

一个更强大的版本:删除文件夹中的所有评论

<?php
$di = new RecursiveDirectoryIterator(__DIR__,RecursiveDirectoryIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($di);
$fileArr = [];
foreach($it as $file){
    if(pathinfo($file,PATHINFO_EXTENSION) == "php"){
        ob_start();
        echo $file;
        $file = ob_get_clean();
        $fileArr[] = $file;
    }
}
$arr = [T_COMMENT,T_DOC_COMMENT];
$count = count($fileArr);
for($i=1;$i < $count;$i++){
    $fileStr = file_get_contents($fileArr[$i]);
    foreach(token_get_all($fileStr) as $token){
        if(in_array($token[0],$arr)){
            $fileStr = str_replace($token[1],'',$fileStr);
        }            
    }
    file_put_contents($fileArr[$i],$fileStr);
}

如果你已经使用过像UltraEdit这样的编辑器,你可以打开一个或多个 PHP 文件,然后使用一个简单的 Find&Replace (CTRL+R)和下面的 Perl regexp

(?s)/\*.*\*/

请注意,上面的正则表达式也会删除 sring 中的注释,即echo "hello/*babe*/"; /*babe*/也将被删除。 因此,如果您只有很少的文件要删除评论,这可能是一个解决方案,为了绝对确保它不会错误地替换不是评论的内容,您必须运行 Find&Replace 命令并在每次替换内容时进行批准。

Bash 解决方案:如果您想从当前目录开始的所有 PHP 文件中递归删除注释,您可以在终端中编写此单行。 (它使用temp1文件来存储 PHP 内容以进行处理)请注意,这将删除带有注释的所有空格。

 find . -type f -name '*.php' | while read VAR; do php -wq $VAR > temp1  ;  cat temp1 > $VAR; done

然后你应该删除temp1文件之后。

如果安装了PHP_BEAUTIFER那么您可以获得格式良好的代码,无需注释

 find . -type f -name '*.php' | while read VAR; do php -wq $VAR > temp1; php_beautifier temp1 > temp2;  cat temp2 > $VAR; done;

然后删除两个文件( temp1temp2

/*
* T_ML_COMMENT does not exist in PHP 5.
* The following three lines define it in order to
* preserve backwards compatibility.
*
* The next two lines define the PHP 5 only T_DOC_COMMENT,
* which we will mask as T_ML_COMMENT for PHP 4.
*/

if (! defined('T_ML_COMMENT')) {
    define('T_ML_COMMENT', T_COMMENT);
} else {
    define('T_DOC_COMMENT', T_ML_COMMENT);
}

/*
 * Remove all comment in $file
 */

function remove_comment($file) {
    $comment_token = array(T_COMMENT, T_ML_COMMENT, T_DOC_COMMENT);

    $input = file_get_contents($file);
    $tokens = token_get_all($input);
    $output = '';

    foreach ($tokens as $token) {
        if (is_string($token)) {
            $output .= $token;
        } else {
            list($id, $text) = $token;

            if (in_array($id, $comment_token)) {
                $output .= $text;
            }
        }
    }

    file_put_contents($file, $output);
}

/*
 * Glob recursive
 * @return ['dir/filename', ...]
 */

function glob_recursive($pattern, $flags = 0) {
    $file_list = glob($pattern, $flags);

    $sub_dir = glob(dirname($pattern) . '/*', GLOB_ONLYDIR);
    // If sub directory exist
    if (count($sub_dir) > 0) {
        $file_list = array_merge(
            glob_recursive(dirname($pattern) . '/*/' . basename($pattern), $flags),
            $file_list
        );
    }

    return $file_list;
}

// Remove all comment of '*.php', include sub directory
foreach (glob_recursive('*.php') as $file) {
    remove_comment($file);
}

对于 ajax/json 响应,我使用以下 PHP 代码从 HTML/JavaScript 代码中删除注释,因此它会更小(我的代码增益约为 15%)。

// Replace doubled spaces with single ones (ignored in HTML any way)
$html = preg_replace('@(\s){2,}@', '\1', $html);
// Remove single and multiline comments, tabs and newline chars
$html = preg_replace(
    '@(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|((?<!:)//.*)|[\t\r\n]@i',
    '',
    $html
);

简短而有效,但如果您的代码具有 $itty 语法,则会产生意想不到的结果。

在命令提示符(即cmd.exe )中运行命令php --strip file.php ,然后浏览到http://www.writephponline.com/phpbeautifier

在这里, file.php是您自己的文件。

1

在 2019 年可以这样工作

<?php
/*   hi there !!!
here are the comments */
//another try

echo removecomments('index.php');

/*   hi there !!!
here are the comments */
//another try
function removecomments($f){
    $w=Array(';','{','}');
    $ts = token_get_all(php_strip_whitespace($f));
    $s='';
    foreach($ts as $t){
        if(is_array($t)){
            $s .=$t[1];
        }else{
            $s .=$t;
            if( in_array($t,$w) ) $s.=chr(13).chr(10);
        }
    }

    return $s;
}

?>

如果您想查看结果,让我们先在 xampp 中运行它,然后您会得到一个空白页面,但是如果您右键单击并单击查看源代码,您将获得您的 php 脚本。 我也更喜欢这个解决方案,因为我用它来加速我的框架一个文件引擎“m.php”,在 php_strip_whitespace 之后,没有这个脚本的所有源代码我观察到的最慢:我做了 10 个基准测试然后我计算了数学平均值(我认为 php 7 正在解析时恢复缺失的 cr_lf 或者当这些缺失时需要一段时间)

php -wphp_strip_whitespace($filename);

文件

根据接受的答案,我也需要保留文件的行号,所以这里是接受的答案的变体:

    /**
     * Removes the php comments from the given valid php string, and returns the result.
     *
     * Note: a valid php string must start with <?php.
     *
     * If the preserveWhiteSpace option is true, it will replace the comments with some whitespaces, so that
     * the line numbers are preserved.
     *
     *
     * @param string $str
     * @param bool $preserveWhiteSpace
     * @return string
     */
    function removePhpComments(string $str, bool $preserveWhiteSpace = true): string
    {
        $commentTokens = [
            \T_COMMENT,
            \T_DOC_COMMENT,
        ];
        $tokens = token_get_all($str);


        if (true === $preserveWhiteSpace) {
            $lines = explode(PHP_EOL, $str);
        }


        $s = '';
        foreach ($tokens as $token) {
            if (is_array($token)) {
                if (in_array($token[0], $commentTokens)) {
                    if (true === $preserveWhiteSpace) {
                        $comment = $token[1];
                        $lineNb = $token[2];
                        $firstLine = $lines[$lineNb - 1];
                        $p = explode(PHP_EOL, $comment);
                        $nbLineComments = count($p);
                        if ($nbLineComments < 1) {
                            $nbLineComments = 1;
                        }
                        $firstCommentLine = array_shift($p);

                        $isStandAlone = (trim($firstLine) === trim($firstCommentLine));

                        if (false === $isStandAlone) {
                            if (2 === $nbLineComments) {
                                $s .= PHP_EOL;
                            }

                            continue; // just remove inline comments
                        }

                        // stand alone case
                        $s .= str_repeat(PHP_EOL, $nbLineComments - 1);
                    }
                    continue;
                }
                $token = $token[1];
            }

            $s .= $token;
        }
        return $s;
    }

注意:这是针对 php 7+(我不关心与旧 php 版本的向后兼容性)。

问题在于,一个不太稳健的匹配算法(例如,简单的正则表达式)将在明显不应该在此处开始剥离:

if (preg_match('#^/*' . $this->index . '#', $this->permalink_structure)) {  

它可能不会影响您的代码,但最终有人会被您的脚本咬到。 因此,您将不得不使用比您预期的更能理解语言的实用程序。

-亚当

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM