A PHP regex to extract php functions from code files

℡╲_俬逩灬. 提交于 2019-12-02 05:51:24

问题


I'm trying to make a PHP regex to extract functions from php source code. Until now i used a recursive regex to extract everything between {} but then it also matches stuff like if statements. When i use something like:

preg_match_all("/(function .*\(.*\))({([^{}]+|(?R))*})/", $data, $matches);

It doesn't work when there is more than 1 function in the file (probably because it uses the 'function' part in the recursiveness too).

Is there any way to do this?

Example file:

<?php
if($useless)
{
  echo "i don't want this";
}

function bla($wut)
{
  echo "i do want this";
}
?>

Thanks


回答1:


regexps is the wrong way to do it. Consider tokenizer or reflection




回答2:


Moved here from duplicate question: PHP, Regex and new lines

Regex solution:

$regex = '~
  function                 #function keyword
  \s+                      #any number of whitespaces 
  (?P<function_name>.*?)   #function name itself
  \s*                      #optional white spaces
  (?P<parameters>\(.*?\))  #function parameters
  \s*                      #optional white spaces
  (?P<body>\{.*?\})        #body of a function
~six';

if (preg_match_all($regex, $input, $matches)) {
  print_r($matches);
}

P.S. As was suggested above tokenizer is preferable way to go.



来源:https://stackoverflow.com/questions/2488498/a-php-regex-to-extract-php-functions-from-code-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!