5

请考虑以下代码,我尝试仅解析文件中的第一个 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 ;
    }
)

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

4

2 回答 2

6

使用 PCRE 编写解析器会给您带来麻烦。我建议首先依赖标记器或反射。然后为 doc 块实际实现一个解析器会更安全,它可以处理phpdoc格式支持的所有情况(所有库也结束了)。

于 2010-05-01T09:08:10.227 回答
0

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

于 2019-03-27T07:29:12.927 回答