0

I have file which has comments at the top.

e.g.

/**
 * Comments for file.
 *
 */

Using PHP, I read content of file using file_get_contents into variable now I want to get value present inside comment. For above example expected result would be

* Comments for file
*
*

Which means I want content inside those /** and */. This file can have multiple comments but I want the very first which is at the top of file.

Any ideas/help please ?

UPDATE:- It is normal text file. Not PHP file.

Umakant Patil
  • 2,157
  • 4
  • 29
  • 54

5 Answers5

6

You can read comment using tokenizer

$source = file_get_contents('example.php');
$tokens = token_get_all($source);
Dipesh Parmar
  • 26,601
  • 7
  • 57
  • 86
1

To complete Dipesh Parmar good answer, an example:

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

Notice: this work if and only if the subject contains <?php, otherwhise comments are seen as simple text by the tokenizer. If <?php is missing you can easily add it before the subject:

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

You can do it systematically, it's not a problem to have two <?php for this task.

Casimir et Hippolyte
  • 85,718
  • 5
  • 90
  • 121
0

Try /\*{2}\s(.*?)\s\*/

Regards.

SamWhan
  • 8,166
  • 1
  • 16
  • 44
  • This does not get me result. May be because of new line characters. I'm using preg_match for this. – Umakant Patil Aug 28 '13 at 05:41
  • I'm not in to PHP at all, but from what I found in [http://stackoverflow.com/questions/8958310/matching-multiple-lines-pattern-via-php-preg-match](this) discussion something like `preg_match('#\*{2}\s(.*?)\s\*/#s',$str,$matches);` might do the trick. The trick being the s after the ending delimiter meaning PCRE_DOTALL, i.e. '.' will match new-line characters. – SamWhan Aug 30 '13 at 06:56
0

If the file is a PHP class, then you can use the ReflectionClass::getDocComment and ReflectionMethod::getDocComment

e.g

$instance = new ClassWithComments();
$reflectionClass = new \ReflectionClass($instance);
echo $reflectionCLass->getDocComment();
AlexP
  • 9,896
  • 1
  • 22
  • 42
0

the standard recommendation is to use a parser instead of regex.

however ^/\*(([^*]*[*]*[^*/])+)\*/ should do the trick in your case. remember to enable multiline-matching in your regex engine. capture group 1 contains the result.

collapsar
  • 16,200
  • 4
  • 33
  • 60