user351657
user351657

Reputation: 361

Read file comments in PHP, NOT file content - forgotten

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?

Upvotes: 5

Views: 7219

Answers (5)

Kalyan Halder
Kalyan Halder

Reputation: 1585

I think you can also try this:

/**
* 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];
}

Upvotes: 1

Wright-Geek
Wright-Geek

Reputation: 395

function find_between($from, $to, $string) {
   $cstring = strstr($string, $from);
   $newstring = substr(substr($cstring, 0, strpos($cstring, $to)), 1);
   return $newstring;
}

Then just call: $comments = find_between('/\*\*', '\*\*/', $myfileline);

Upvotes: 0

svens
svens

Reputation: 11628

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

?>

Upvotes: 17

Kieran Allen
Kieran Allen

Reputation: 942

Is this what you mean?

$file_contents = '/**

sd
asdsa
das
sa
das
sa
a
ad**/';

preg_match('#/\*\*(.*)\*\*/#s', $file_contents, $matches);

var_dump($matches);

Upvotes: 0

gblazex
gblazex

Reputation: 50109

Use this:

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

Upvotes: 0

Related Questions