-2

How can I read the comment block annotations in the PHP file dynamically?

Example:-

<?php
/**
* @author John Doe (jdoe@example.com)
* @copyright MIT
*/

How can I get the @author using another php file?

Youssef Siam
  • 194
  • 1
  • 8
  • 1
    See https://stackoverflow.com/q/4702356/231316, https://stackoverflow.com/q/2531085/231316 and many others – Chris Haas Nov 09 '20 at 15:45
  • @ChrisHaas Thanks, man! but my question was about parsing file DocBlock not class or method DocBlock – Youssef Siam Nov 09 '20 at 15:58
  • 1
    It might also be worth looking into [this](https://stackoverflow.com/a/13391784/231316). Although that is specifically for WordPress, it is also about parsing comments at a specific location in a file using a pattern that is similar to what you are looking at, with wildcard support for the various – Chris Haas Nov 09 '20 at 16:27
  • @ChrisHaas That exactly what I am looking for! – Youssef Siam Nov 09 '20 at 16:44
  • Does this answer your question? [How is PHP used to parse comments / headers for themes and plugins?](https://stackoverflow.com/questions/13391556/how-is-php-used-to-parse-comments-headers-for-themes-and-plugins) – β.εηοιτ.βε Nov 09 '20 at 21:14

1 Answers1

1

don't think there's any "good way" to do it, unfortunately. just regex it, eg

<?php
/**
* @author John Doe (jdoe@example.com)
* @copyright MIT
*/
/**
* @author Moe (moe@example.com)
* @copyright MIT
*/

$php_file = __FILE__;
$content = file_get_contents($php_file);
$rex = <<<'REX'
/\n\*\s*\@author\s*(?<author>[^\n]+?)\s*?$/m
REX;
$authors = [];
if(preg_match_all($rex,$content,$matches)){
    $authors += $matches["author"];
}
var_dump($authors);

and even that is not particularly reliable, but that specific script yields

array(2) {
  [0]=>
  string(27) "John Doe (jdoe@example.com)"
  [1]=>
  string(21) "Moe (moe@example.com)"
}
hanshenrik
  • 19,904
  • 4
  • 43
  • 89