I am trying to get comments from a specific .php
file on my server to parse its variables. I thought Ii found an easy way to do this, however the function I use returns nothing, although I explicitly have comments in the file.
Here are the comments I use:
Here is my code:
function GetComments($filename) { $expr = "/((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))/"; $file = fopen($filename, "r"); $length = filesize($filename); $comments = fread($file, $length); fclose($file); preg_match_all($expr, $comments, $matches); foreach($matches[0] as $id => $variable){ $comments = str_replace($variable,'',$comments); } return $comments; }
Is there something I'm doing wrong? Because if this is so, I am clearly looking at it.
Any help would be greatly appreciated.
EDIT:
I found the answer:
First of all, I should probably have noted in my question that I am trying to write a system for reading plugins. These plugin files should contain a comment block at the top containing variables such as the author of the plugin, website, email, etc.
so here is what i did:
I took an example of assemblies to modify my function to get comments and variables.
Then I changed the code a bit to fit my needs:
public function GetComments($filename) { $docComments = array_filter(token_get_all(file_get_contents($filename)), function($entry) { return $entry[0] == T_COMMENT; }); $fileDocComment = array_shift($docComments); $regexp = "/\@.*\:\s.*\r/"; preg_match_all($regexp, $fileDocComment[1], $matches); for($i = 0; $i < sizeof($matches[0]); $i++) { $params[$i] = split(": ", $matches[0][$i]); } return($params); }
I put the result of the code that I was given through the regular expression, the result is an array containing the parameters and their values. Then I used the split function to give me individual parameters and values, so I could return them to the variable that called the function.
For this to work correctly, I had to change the style of the comment that I used from
to
makes it a normal comment block, not a doc comment block.
And it also allowed me to use ':' as a template for the split function.
It may not be so effective in the eyes of some. As Ms. Valle noted, βWhat will change your style of commentary?β I will be the only one working on this project and writing plugins. Therefore, itβs not too difficult for me to keep the comment style the same in every script plugin.
This method works great for me.
Thanks everyone for the help on this.