已编辑:该函数的真实名称是CB_t
考虑一个包含多个文件和文件夹的项目。 在整个项目中,我们使用不同的参数多次调用 CB_t($string='') 函数。 我需要的是以编程方式查找该函数被调用的所有时间,并使用参数创建一个数组。该参数始终是一个字符串。
代码示例:
文件1:
<?php
# Some code ....
$a = CB_t('A');
$b = CB_t("B");
# more code ...
文件2:
<?php
# Some code ....
$c = CB_t("ABC");
$d = CB_t('1938');
# more code ...
我需要的是解析所有代码并创建一个包含所有参数的数组。 对于上述示例,数组应如下所示:
['A','B','ABC','1938']
下面是我到目前为止所尝试的,但没有给出好的结果,因为该函数有时使用简单引号调用,有时使用双引号或使用大写或小写。
$search = "F(";
$path = realpath(ROOT); // ROOT defined as project root folder
$fileList = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST);
$count = 0;$counter = 0;
foreach ($fileList as $item)
{
if ( $item->isFile() && substr($item->getPathName(), -4) =='.php') // #1
{
$counter++;
$file = file_get_contents($item->getPathName());
if( strpos($file,trim($search)) !== false) {
$count++;
echo "<br>File no : ".$count;
echo "<br>Filename : ".$item->getFileName();
echo "<br>File path : ".$item->getPathName();
echo "<hr>";
} // End file is php
unset($file);
} // End if #1
} // End foreach
我认为可以用正则表达式以某种方式解决这个问题,但我不能很好地控制这部分。
提前致谢!
最佳答案
这可能有效。一些额外的注释用于分支重置。捕获组 1 将
包含字符串内容。
Edit - If you want to make the regex into a C-style string, here it is:
"[Ff]\\s*\\(\\s*(?|\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"|'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)')\\s*\\)"
---------------------------------------------------------
# [Ff]\s*\(\s*(?|"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)')\s*\)
[Ff]
\s*
\(
\s*
(?|
"
br 1 ( # (1 start)
[^"\\]*
(?: \\ . [^"\\]* )*
1 ) # (1 end)
"
|
'
br 1 ( # (1 start)
[^'\\]*
(?: \\ . [^'\\]* )*
1 ) # (1 end)
'
)
\s*
\)
编辑2 - 使用示例:
$string =
"
f('hello')
F(\"world\")
";
preg_match_all
(
"/[Ff]\\s*\\(\\s*(?|\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"|'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)')\\s*\\)/",
$string,
$matches,
PREG_PATTERN_ORDER
);
print_r( $matches[1] );
-----------------------------
Result:
Array
(
[0] => hello
[1] => world
)
关于php - 如何解析 PHP 项目,查找代码中出现的函数并检测每次调用中的调用参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19279353/