PHP preg_match_all REGEX查找所有“文件(...)”函数

时间:2017-06-28 17:06:28

标签: php regex preg-match-all

我正在尝试解析包含PHP文件转储的字符串,以匹配PHP本机函数file()的所有匹配项。我正在使用preg_match_all,其REGEX未按预期完全正常工作。

事实上,因为我希望匹配file()函数的所有匹配项,所以我不希望匹配$file()$fileis_file()等结果

这是我试图匹配所有file()出现的PHP代码:

<?php

$x = file('one.php');
file('two.php');

// 

function foo($path)
{
    return file($path);
}

function inFile()
{
    return "should not be matched";
}file('next_to_brackets.php');

foo('three.php');
file('four.php'); // comment

$file = 'should not be matched';

$_file = 'inFile';
$_file();

file('five.php');

我正在使用的REGEX如下:

/[^A-Za-z0-9\$_]file\s*\(.*?(\n|$)/i

 [^A-Za-z0-9\$_]  Starts with anyting except for letters, numbers, underscores and dollars.
 file             Continue with "file" word.
 \s*              Capture any space after "file" word.
 \(               After the spaces there should be an opening parenthesis.
 .*?              Capture any list of characters (the arguments).
 (\n|$)           Stop capturing until a new line or the end of haystack is found.
 /i               Used for case-insensitive matches.

使用此PHP代码测试结果:

preg_match_all('/[^A-Za-z0-9\$_]file\s*\(.*?(\n|$)/i', $string, $matches);
print_r($matches[0]);
/*
//Prints:
Array
(
    [0] =>  file('one.php');

    [1] =>  file($path);

    [2] => }file('next_to_brackets.php');

    [3] => 
file('four.php'); // comment

    [4] => 
file('five.php');
)
*/

由于某些原因,当这是一个有效的函数而不是变量时,我的REGEX不会返回第二次出现的file('two.php');。这肯定是因为它正好位于另一场匹配($x = file('one.php');)之下。

有关如何在包含PHP代码的字符串中匹配精确PHP函数的任何建议吗?

谢谢!

0 个答案:

没有答案