Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP read file comments NOT file content - forgotten

Tags:

comments

php

I need to read the first "batch" of comment in a PHP file. An example would be:

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

I need to read the first comment inside another file, but how do I get the /** This is some basic file info **/ as a string?

like image 905
user351657 Avatar asked Dec 08 '22 02:12

user351657


1 Answers

There's a token_get_all($code) function which can be used for this and it's more reliable than you first might think.

Here's some example code to get all comments out of a file (it's untested, but should be enough to get you started):

<?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];
    }

?>
like image 173
svens Avatar answered Dec 23 '22 12:12

svens