正在字符串中查找注释


Finding comments in a string

我有一个文件,上面有注释。

例如

/**
 * Comments for file.
 *
 */

使用PHP,我使用file_get_contents将文件的内容读取到变量中,现在我想获得注释中的值。对于上面的例子,预期的结果是

* Comments for file
*
*

这意味着我想要/**和*/中的内容。这个文件可以有多个注释,但我想要第一个,它在文件的顶部。

有什么想法/帮助吗?

更新:-这是一个普通的文本文件。不是PHP文件。

您可以使用标记化器读取注释

$source = file_get_contents('example.php');
$tokens = token_get_all($source);

要完成Dipesh-Parmar的好答案,一个例子:

$subject =<<<'LOD'
sdf df sdf sdf 
sdf sdf sdf sdf
<?php 
/**
* Youhou!!
*
* HiHa!
*
*/
LOD;
$tokens = token_get_all($subject);
foreach($tokens as $token) {
    if (is_array($token)&&$token[0]==T_DOC_COMMENT) {
        echo substr(substr($token[1],4),0,-3);
        break;
    }
}

注意:当且仅当主题包含<?php时,此操作才有效,而其他注释则被标记器视为简单文本。如果<?php缺失,您可以很容易地将其添加到主题之前:

$tokens = token_get_all('<?php'.$subject);

你可以系统地完成,这项任务有两个<?php不是问题。

如果文件是PHP类,则可以使用ReflectionClass::getDocCommentReflectionMethod::getDocComment

例如

$instance = new ClassWithComments();
$reflectionClass = new 'ReflectionClass($instance);
echo $reflectionCLass->getDocComment();

标准建议使用解析器而不是regex。

然而,^/'*(([^*]*[*]*[^*/])+)'*/应该在您的情况下发挥作用。记住在正则表达式引擎中启用多行匹配。捕获组1包含该结果。

尝试/'*{2}'s(.*?)'s'*/

谨致问候。