【问题标题】:PHP read file comments NOT file content - forgottenPHP读取文件注释而不是文件内容 - 忘记了
【发布时间】:2011-03-14 19:49:56
【问题描述】:

对不起,人们忘记了这一点,我需要阅读 php 文件中的第一批“批”注释示例:

<?php
/** This is some basic file info **/
?>
<?php This is the "file" proper" ?>

我需要阅读另一个文件中的第一条评论,但我完全忘记了如何获取 /** 这是一些基本文件信息 **/ 作为字符串对不起,但提前感谢

【问题讨论】:

  • &lt;?php "\/** t **\/" ?&gt; ?我实际上不知道,但这是我会尝试的第一件事
  • Thnk Mechko,但在遥远的过去,我找到了一个函数——不记得它是“php 函数”还是自定义编写的函数

标签: php comments


【解决方案1】:

有一个token_get_all($code) 函数可用于此目的,它比您最初想象的更可靠。

下面是一些示例代码,用于从文件中获取所有 cmets(未经测试,但应该足以让您入门):

<?php

    $source = file_get_contents( "file.php" );

    $tokens = token_get_all( $source );
    $comment = array(
        T_COMMENT,      // All comments since PHP5
        T_ML_COMMENT,   // Multiline comments PHP4 only
        T_DOC_COMMENT   // PHPDoc comments      
    );
    foreach( $tokens as $token ) {
        if( !in_array($token[0], $comment) )
            continue;
        // Do something with the comment
        $txt = $token[1];
    }

?>

【讨论】:

  • 嘿,我只会稍微改变一下...将break 更改为continue,这样您就可以继续在内容中找到所有cmets。
  • 按照@CayceK 的建议,我已将break 更改为continue
  • @davewoodhall 遗憾的是它不会保留。所有问题的“更改”队列每次都会拒绝您。这只是一个很小的更改,由代码的用户来进行更改。不过你的努力得到了记录!
  • 大家好,这显然是我的代码错误,所以我进行了编辑。抱歉,之前没有打扰,因为答案已经有好几年了;)。
【解决方案2】:

我想你也可以试试这个。

/**
* Return first doc comment found in this file.
* 
* @return string
*/
function getFileCommentBlock($file_name)
  {
    $Comments = array_filter(
       token_get_all( file_get_contents( $file_name ) ),function($entry) {
           return $entry[0] == T_DOC_COMMENT;
       }
   );
    $fileComment = array_shift( $Comments );
    return $fileComment[1];
}

【讨论】:

    【解决方案3】:

    使用这个:

    preg_match("/\/\*\*(.*?)\*\*\//", $file, $match);
    $info = $match[1];
    

    【讨论】:

      【解决方案4】:

      这是你的意思吗?

      $file_contents = '/**
      
      sd
      asdsa
      das
      sa
      das
      sa
      a
      ad**/';
      
      preg_match('#/\*\*(.*)\*\*/#s', $file_contents, $matches);
      
      var_dump($matches);
      

      【讨论】:

      • kieran - 看起来你也有“其中一个”类型的星期一。很高兴再次“撞”到你:)
      • 嘿,是的,我在工作中度过了非常富有成效的一天.. 咳嗽
      【解决方案5】:
      function find_between($from,$to,$string){
         $cstring = strstr($string, $from);
         $newstring = substr(substr($cstring,0,strpos($cstring,$to)),1);
         return $newstring;
      }
      

      然后拨打:$comments = find_between('/\*\*','\*\*/',$myfileline);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-14
        • 1970-01-01
        相关资源
        最近更新 更多