【发布时间】:2011-02-14 12:17:23
【问题描述】:
请考虑以下代码,我试图仅解析文件中的第一个 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 ;
}
)
如何更改我的代码以便只解析第一个注释块(换句话说:在遇到第一个“*/”后应该停止解析?
【问题讨论】:
-
考虑像
$s = '/** not a phpDoc @file ... */';这样的字符串放在第一个phpDoc之前的情况。换句话说:使用正则表达式,您将获得 100% 可靠的解决方案。
标签: php regex parsing comments phpdoc