You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PHP读取代码文件头部注释中的文档信息

PHP读取代码注释块指定字段的实现方法

实现思路

  • 读取目标PHP文件的完整内容
  • 用正则匹配到你需要的多行注释块
  • 对注释内容做二次解析,提取键值对字段

可运行示例代码

// 读取目标文件内容,替换为你的实际文件路径
$fileContent = file_get_contents('target.php');

// 匹配/* */包裹的多行注释块
preg_match('/\/\*.*?\*\//s', $fileContent, $matches);
if (empty($matches)) {
    die('未找到匹配的注释块');
}
$commentContent = $matches[0];

// 解析注释内的键值对
$fields = [];
// 匹配每行的 键 : 值 格式,忽略前后的-和空格
preg_match_all('/-\s*([^:]+?)\s*:\s*([^\s-].*?)\s*-\s*$/m', $commentContent, $fieldMatches);
foreach ($fieldMatches[1] as $index => $key) {
    $fields[trim($key)] = trim($fieldMatches[2][$index]);
}

// 输出测试结果
print_r($fields);

返回结果示例

Array
(
    [PHP Version] => 4.0
    [This code was created on] => 2021/11/29 at 00:10
    [Checksum] => d8d8000bfc33a4eba1e6b51b8fc71312
)

注意事项

  • 如果文件内存在多个/* */注释块,可以调整正则规则增加过滤条件,比如匹配注释块内是否包含PHP Version字段来定位目标块
  • 如果是读取类/函数的官方文档注释(DocBlock),也可以直接用PHP内置的Reflection反射类实现,不用自己写正则解析

内容的提问来源于stack exchange,提问作者emn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:15:03