我正在做一些自制的自动化文档,因为我的代码库布局不是很标准,我想知道读取PHP文件和获取注释块内容的最佳方法是什么.我能想到的唯一方法是打开文件并逐行阅读,但是想到可能有一些内置的魔法会为我解析文档,类似于Reflection函数.
每个文件的基本布局如下:
<?php // $Id$
/**
* Here is this script's documentation, with information in pseudo-javadoc
* type tags and whatnot.
*
* @attr something some information about something
* @attr etc etc etc
*/
// rest of the code goes here.
Run Code Online (Sandbox Code Playgroud)
请务必注意,这些文件中没有定义任何函数或类.这些评论与整个剧本有关.
请考虑以下代码,我试图仅解析文件中的第一个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)
Run Code Online (Sandbox Code Playgroud)
除了@todo之后的所有内容(包括bar()注释块和代码)被视为以下值之外,这几乎可以正常工作@todo:
Array (
[file] => …Run Code Online (Sandbox Code Playgroud)