Reputation: 8111
I have a script that recursively scans a directory pulling out class names from php files, and storing those classes names in an array. This is working nicely even through the rather large Zend Framework library folders.
The issue is that classes that extend other classes are not being 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 that the last \s* is not right; there should be something there that can catch "{" or " extends Some_Other_Class {" .
Upvotes: 2
Views: 4385
Reputation: 21
'/class[\s\n]+([a-zA-Z0-9_]+)[\s\na-zA-Z0-9_]+\{/'
This one works better because it supports classes who extend or implement.
Example:
class blah implements base
{
will match.
Upvotes: 2
Reputation: 8111
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);
}
Seems to work pretty well. Found it in a another Coda Plugin that does something similar. The only catch is that it seems to hang sometimes. Not sure if that's a bug or it just being slow.
Upvotes: 0
Reputation: 3138
Your pattern should simply take the first word following the class
keyword to be the class name as opposed to your current pattern which looks for a single word between the class
keyword and opening brace {
. This is problematic where your class extends another because there isn't just a single word between the delimiters and thus the pattern wouldn't match.
Here's a pattern to try out:
/^\s*class\s+([a-zA-Z0-9_]+)/
Upvotes: 0