如何解析PHP PHP样式注释块? [英] How to parse a phpDoc style comment block with PHP?
问题描述
请考虑以下代码,我试图只解析一个文件中的第一个phpDoc样式注释(不使用任何其他库)(文件内容放在$ data变量用于测试目的):
Please consider the following code with which I'm trying to parse only the first phpDoc style comment (not using any other libraries) in a file (file contents put in $data variable for testing purposes):
$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
:
This almost works, except for the fact that everything after @todo (including the bar()
comment block and code) is considered the value of @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 ;
}
)
我的代码需要如何改变,使得只有第一个注释块
How does my code need to be altered so that only the first comment block is being parsed (in other words: parsing should stop after the first "*/" encountered?
推荐答案
使用PCRE编写解析器将会解析(换句话说:解析应该在遇到第一个* /我建议您依赖分词器或反射。因此,实际实现doc块的解析器更加安全,可以处理 phpdoc 支持的所有情况格式(所有库都结束做)。
Writing a parser using PCRE will lead you to troubles. I would suggest to rely on the tokenizer or reflection first. Then it is safer to actually implement a parser for the doc block, which can handle all situations supported by the phpdoc format (what all libs ended to do as well).
这篇关于如何解析PHP PHP样式注释块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!