Preg_match class name from PHP file
I have a script that scans a directory recursively, pulling the class names from php files and storing the class names in an array. This works great even through the fairly large Zend Framework libraries.
The problem is that classes that extend other classes are not included in the array.
Here is my current preg_match:
if (preg_match("/class\s*(\w*)\s*\{/i",strip_comments(file_get_contents($file)),$matches)) $classes[] = $matches[1];
I know the last \ s * is wrong; there should be something that can catch "{" or "extends Some_Other_Class {".
a source to share
Your template should just take the first word following the keyword class
to be the class name, unlike your current template, which looks for one word between the keyword class
and the open parenthesis {
. This is problematic when your class extends another, because not only one word exists between the delimiters, and therefore the pattern will not match.
Here's a sample to try:
/^\s*class\s+([a-zA-Z0-9_]+)/
a source to share
I ended up using this foreach php file in the include path:
$handle = @fopen($path.'/'.$dir, "r");
$stop=false;
if ($handle)
{
while (!$stop&&!feof($handle))
{
$line = fgets($handle, 4096);
$matches=array();
if (preg_match('#^(\s*)((?:(?:abstract|final|static)\s+)*)class\s+'.$input.'([-a-zA-Z0-9_]+)(?:\s+extends\s+([-a-zA-Z0-9_]+))?(?:\s+implements\s+([-a-zA-Z0-9_,\s]+))?#',$line,$matches))
{
$stop=true;
$classes[]=$matches[3];
}
}
fclose($handle);
}
Everything seems to be working well. Found it in another Coda plugin that does something similar. The only catch is that it hangs sometimes. Not sure if this is a bug or if it is just slow.
a source to share