How to parse a phpDoc style comment block with PHP?

别来无恙 提交于 2019-12-10 16:00:04

问题


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)

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?


回答1:


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).




回答2:


The Php Comment Manager script allows parsing DocBloc comments of methods. It supports parsing method description, @param and @return tags. It can be extended to support custom DocBloc tags



来源:https://stackoverflow.com/questions/2749301/how-to-parse-a-phpdoc-style-comment-block-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!