Reputation: 4306
How can I extract all function names from a PHP file?
The file has many functions that look more or less like the following. Is a regular expression the best way to do it?
public function someFunction(
private function anotherOne(
Upvotes: 2
Views: 4967
Reputation: 151126
You can write another PHP file to grep for that, or if you have Linux or Mac OS X, you can use something like:
grep -P "function\s+\w" myfile.php
Upvotes: 1
Reputation: 47321
If the PHP file is syntactically correct and only contains function only, you can store the result of get_defined_functions
into an array (anyway, is return an array).
include_once
the PHP file, compare the latest get_defined_functions
with the previous array (like array_diff
). Whichever results returned by array_diff
are the functions define in the PHP file.
If is an object declaration, the above won't work, although you can make use of function get_class_method
, but it is not able to return protected and private methods.
OR
ob_start();
highlight_string(file_get_contents('class.php'));
$html = ob_get_contents();
ob_end_clean();
$dom = new DomDocument;
$dom->loadHTML($html);
You can have a list of DOM with a style attribute you can filter with.
Upvotes: 2
Reputation: 4075
If your PHP file contains a class which are having methods like above as you mentioned, after including file, you can use get_class_methods
function of PHP which requires only the classname and it will return the methods of a mentioned class. For more information, see get_class_methods.
However, if you are sure about classes but don't know the names of it then you can use the first get_declared_classes function to get classes, and then you can use the above mentioned function to the methods of those classes.
Upvotes: 1
Reputation: 10351
You could find them with a regular expression:
# The Regular Expression for Function Declarations
$functionFinder = '/function[\s\n]+(\S+)[\s\n]*\(/';
# Init an Array to hold the Function Names
$functionArray = array();
# Load the Content of the PHP File
$fileContents = file_get_contents( 'thefilename.php' );
# Apply the Regular Expression to the PHP File Contents
preg_match_all( $functionFinder , $fileContents , $functionArray );
# If we have a Result, Tidy It Up
if( count( $functionArray )>1 ){
# Grab Element 1, as it has the Matches
$functionArray = $functionArray[1];
}
Upvotes: 4