如何用PHP解析phpDoc样式的注释块?

时间:2010-05-01 08:24:43

标签: php regex parsing comments phpdoc

请考虑以下代码,我试图仅解析文件中的第一个phpDoc样式注释(不使用任何其他库)(文件内容放在$ data变量中用于测试目的):

$data = "
/**
 * @file    A lot of info about this file
 *          Could even continue on the next line
 * @author  me@example.com
 * @version 2010-05-01
 * @todo    do stuff...
 */

/**
 * Comment bij functie bar()
 * @param Array met dingen
 */
function bar($baz) {
  echo $baz;
}
";

$data =  trim(preg_replace('/\r?\n *\* */', ' ', $data));
preg_match_all('/@([a-z]+)\s+(.*?)\s*(?=$|@[a-z]+\s)/s', $data, $matches);
$info = array_combine($matches[1], $matches[2]);
print_r($info)

除了@todo之后的一切(包括bar()注释块和代码)被视为@todo的值

之外,这几乎可以正常运行。

Array (
    [file] => A lot of info about this file Could even continue on the next line
    [author] => me@example.com
    [version] => 2010-05-01
    [todo] => do stuff... /

    /** Comment bij functie bar()
    [param] => Array met dingen /
    function bar() {
      echo ;
    }
)

我的代码如何被修改以便只解析第一个注释块(换句话说:解析应该在遇到第一个“* /”之后停止?

2 个答案:

答案 0 :(得分:6)

使用PCRE编写解析器会导致麻烦。我建议先依靠tokenizerreflection。然后,为doc块实际实现一个解析器更安全,它可以处理phpdoc格式支持的所有情况(所有libs也会这样做)。

答案 1 :(得分:0)

Php Comment Manager脚本允许解析方法的DocBloc注释。它支持解析方法描述,@ param和@return标记。可以扩展以支持自定义DocBloc标签

相关问题