我在尝试做一个PHP regex提取功能,从php源代码。直到现在我用递归regex取之间的一切{}但后来也符合这样的东西如果发言。当我使用一些东西,如:

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

它不工作的时候,有1个多功能的文件(可能是因为它采用的功能部分,在recursiveness太)。

是否有任何方式做到这一点?

例文件:

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

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

感谢

有帮助吗?

解决方案

regexp是错误的方式做到这一点。考虑 tokenizer反射

其他提示

搬到这里从重复的问题: PHP,正则表达式和新线

正则表达式溶液:

$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。 如上述标记生成器建议优选的路要走。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top