在PHP中阅读文件注释,而不是文件内容 - 忘记了

5
我需要读取PHP文件中的第一个“批次”注释。例如:

<?php
/** This is some basic file info **/
?>
<?php This is the "file" proper" ?>

我需要在另一个文件中读取第一个注释,但是如何将/** This is some basic file info **/作为字符串获取呢?


<?php "/** t **/" ?> 我其实不确定,但这是我会尝试的第一件事。 - Ritwik Bose
谢谢Mechko,但是在遥远的过去的某个地方,我找到了一个可以做到这一点的函数 - 不记得它是一个“php函数”还是自定义编写的。 - user351657
5个回答

17

有一个token_get_all($code)函数可以用于此操作,它比您最初想象的要可靠。

以下是一些示例代码,可将文件中的所有注释提取出来(未经测试,但应足以让你开始):

<?php

    $source = file_get_contents( "file.php" );

    $tokens = token_get_all( $source );
    $comment = array(
        T_COMMENT,      // All comments since PHP5
        T_ML_COMMENT,   // Multiline comments PHP4 only
        T_DOC_COMMENT   // PHPDoc comments      
    );
    foreach( $tokens as $token ) {
        if( !in_array($token[0], $comment) )
            continue;
        // Do something with the comment
        $txt = $token[1];
    }

?>

2
嘿,我只会稍微修改一下...将break改为continue,这样你就可以继续查找内容中的所有注释。 - Cayce K
正如@CayceK所建议的那样,我已将break更改为continue - davewoodhall
@davewoodhall,不幸的是它无法保留。所有问题的“更改”队列每次都会拒绝您。这只是一个小变化,由代码用户进行更改。但是我们注意到了您的努力! - Cayce K
嘿,大家好,我的代码显然有错误,所以我进行了编辑。抱歉之前没有注意到,因为这个答案已经有几年了;)。 - svens

1
我认为你也可以尝试这个:

/**
* Return first doc comment found in this file.
*
* @return string
*/
function getFileCommentBlock($file_name)
{
    $Comments = array_filter(
            token_get_all(file_get_contents($file_name)), function($entry) {
                return $entry[0] == T_DOC_COMMENT;
            }
        );

    $fileComment = array_shift($Comments);
    return $fileComment[1];
}

0

使用这个:

preg_match("/\/\*\*(.*?)\*\*\//", $file, $match);
$info = $match[1];

0
function find_between($from, $to, $string) {
   $cstring = strstr($string, $from);
   $newstring = substr(substr($cstring, 0, strpos($cstring, $to)), 1);
   return $newstring;
}

然后只需调用:$comments = find_between('/\*\*', '\*\*/', $myfileline);


0

你是指这个吗?

$file_contents = '/**

sd
asdsa
das
sa
das
sa
a
ad**/';

preg_match('#/\*\*(.*)\*\*/#s', $file_contents, $matches);

var_dump($matches);

Kieran - 看起来你今天也是那种“糟糕”的星期一。很高兴再次“撞见”你 :) - jim tollan
嘿,是的,我在工作中度过了非常有生产力的一天...... 咳嗽 - Kieran Allen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接