+ -
当前位置:首页 → 问答吧 → 完美取得代码中的注释

完美取得代码中的注释

时间:2009-04-16

来源:互联网

本帖最后由 liexusong 于 2009-4-16 19:12 编辑

看到很多人都问怎么去掉注释,所以发个取得代码中的注释, 算法比较简单,而且准确率高!
[php]
function get_comments($code) {
    $is_qutoe_one = false;
    $is_qutoe_two = false;
    $is_block_comment = false;
    $is_line_comment  = false;
    $comments = array();
    $len = strlen($code);
    $comment = '';
    for($i = 0; $i < $len; $i++) {
        if($code{$i} == '"') {
            $is_qutoe_one = $is_qutoe_one ? false : true;
        }
        
        if($code{$i} == "'") {
            $is_qutoe_two = $is_qutoe_two ? false : true;
        }
        
        if(isset($code{$i + 1}) && $code{$i}.$code{$i + 1} == '//' && !$is_qutoe_two && !$is_qutoe_one && !$is_block_comment) {
            $is_line_comment = true;
        }
        
        if(isset($code{$i + 1}) && $code{$i}.$code{$i + 1} == '/*' && !$is_qutoe_two && !$is_qutoe_one && !$is_line_comment) {
            $is_block_comment = true;
        }
        
        if($is_line_comment) {
            if($code{$i} != "\n" && $code{$i} != "\r") $comment .= $code{$i};
            if($code{$i} == "\n" || $code{$i} == "\r" || $i == $len - 1) {
                $is_line_comment = false;
                $comments[] = $comment;
                $comment = '';
            }
        }
        
        if($is_block_comment) {
            if($code{$i - 1}.$code{$i} != '*/') $comment .= $code{$i};
            if($code{$i - 1}.$code{$i} == '*/') {
                $is_block_comment = false;
                $comments[] = $comment.$code{$i};
                $comment = '';
            }
        }
    }
    return($comments);
}

$php = <<<PHP
    \$var = "Hello World";
    echo "Hello World";//this is comment
    \$var2 = "http://www.google.cn";//my comment too
    //this is comment else
    //this is comment too//*this is block comment*/
    /*this is block comment*/
    \$string = 'http://www.baidu.com';//this is baidu
    /**
    I am block comment too
    **/
    /*this is block comment*/
PHP;
print_r(get_comments($php));
[/php]

作者: liexusong   发布时间: 2009-04-16

不用这么麻烦.去看看Tokenizer Functions

作者: TankMe   发布时间: 2009-04-16

不错的想法。

作者: sueswriter   发布时间: 2009-04-16

楼上AD!封号!

作者: liexusong   发布时间: 2009-04-17