0

I want to find all functions in a file - thats no problem:

preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);

The problem is that if there are Javascript functions, they will get in the scheme, too.

Is it even possible to get only PHP-functions. One indicator would be the <script>-Tag, but I have no Idea how to only track functions, which are not surounded by the script-Tag!

Thank you!

Haudegen
  • 498
  • 1
  • 4
  • 17
  • 1
    this opens a HUGE ball of wax. there's any number of ways of "hiding" script tags. e.g. there's js which PRODUCES js, and you'll end up with silly things like `document.write('')` or `' ?>`. good luck... – Marc B Aug 04 '15 at 16:02
  • 1
    http://stackoverflow.com/questions/2197851/function-list-of-php-file – Kevin Seifert Aug 04 '15 at 16:02
  • @MarcB You are right! It just would get messy - but fortunately I got another solution. It seems to work :-) Thanks anyways! – Haudegen Aug 04 '15 at 16:12

2 Answers2

3

I had THE idea 2 seconds after writing the question.

$data = file_get_contents($file);   

$data = preg_replace("/<script[^>]*>[\s\S]*?<\/script>/", "", $data);
preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);

Just delete all the <script>-Tags! If you would need them later, you also could save them (instead of replacing them) and add them later!

Just if someone else will have the same problem!

Haudegen
  • 498
  • 1
  • 4
  • 17
2

One option would be to remove all <script>...</script> tags before processing, but this assumes that you will only have JavaScript in these tags directly in the file. If you have a function or a library that generates HTML for you, it is possible for you to output JavaScript code without explicitly having the <script>...</script> tags in your PHP document. The issue is that you are using pattern matching, which can lead to an array of false positives.

To remove these false positives all together, you could use the PHP ReflectionFunction class to determine which functions are defined in PHP and which are not. Once you have an array of possible function names, use the following:

$data = file_get_contents($file);   
$outputData;
$validMatches=array();
preg_match_all("/function[\s\n]+(\S+)[\s\n]*\(/", $data, $outputData);

foreach($outputData[1] as $match) {
    $isValid=true;
    try {
        $reflection = new \ReflectionFunction($match);
    } catch (\ReflectionException $e) {
        $isValid=false;
    }
    if($isValid == true) {
        $validMatches[]=$match;
    }
}

This is more verbose but it will guarantee that you will get a list of only PHP function names.

acharris
  • 31
  • 4