首页 > 解决方案 > 如何在 preg_match php 中的同一正则表达式中查找任何关键字

问题描述

我有一个文本文件,我想像文件中有很多行一样搜索它,我想搜索每一行,它应该返回该行具有关键字“function”,并且应该从同一行调用该函数。

表示我想在同一个正则表达式中搜索关键字。例如。请检查以下test.txt是否 txt 文件的第 2 行有function f3但在该行中没有任何调用函数f3,因此不应计算该行。但是文本文件的第 3 行有function f1并且f1()也从同一行调用,所以它会被计数。

以下是我要从中搜索行的文件内容。

test.txt

$xwbl209= "SN),AK mtyCcMXQHJ.T0-3qjfY5GnRl";
$k =5; function f3($a,$b,$c){ /*...*/ };
function f1(){ /*...*/ }; $a=1; $b=5; f1();
$aayw572 = f3($xwbl209{5},'',$xwbl209{10});
$k=10; function f2(){ /*...*/ }; $j=1; f1();
$bhzs038 = f3($xwbl209{5},$xwbl209{6},$xwbl209{8});
$aa = "aa"; function f4(){ /*...*/ }; $b=1; f4();
$b = "b"; function f5(){ /*...*/ }; $b=1; f4();
$aa = "aa"; function f6(){ /*...*/ }; $b=1; f6();
$bhzs038 = f3($xwbl209{5},$xwbl209{6},$xwbl209{8});

从下面的代码我正在尝试。

$lines = explode("\n", file_get_contents('test.txt'));
$new_line = array();
foreach($lines as $line){
    if(preg_match(/somthing pattern/, $line)){
        $new_line[] = $line;    
    }
}
print_r($new_line);

我也尝试了以下模式,但它不起作用。 /function ([^\(])+\(.*$1\(\).*/g

的输出$new_line应如下所示。

function f1(){ /*...*/ }; $a=1; $b=5; f1();
$aa = "aa"; function f4(){ /*...*/ }; $b=1; f4();
$aa = "aa"; function f6(){ /*...*/ }; $b=1; f6();

你能帮我吗?谢谢!!

标签: phpregexfind

解决方案


一种选择可能是使用

\bfunction\h+(\w+\([^()]*\)).*\1;

解释

  • \bfunction\h+一个单词边界、匹配function和 1+ 个水平空白字符
  • (捕获组 1
    • \w+\([^()]*\)匹配 1+ 个单词字符和来自(...)
  • )关闭组 1
  • .*\1;使用反向引用在同一行中匹配第 1 组中捕获的内容,\1然后;

正则表达式演示

$lines = explode("\n", file_get_contents('test.txt'));
$new_line = array();
foreach($lines as $line){
    if(preg_match('/\bfunction\h+(\w+\([^()]*\)).*\1;/', $line)){
        $new_line[] = $line;
    }
}
print_r($new_line);

输出

Array
(
    [0] => function f1(){ /*...*/ }; $a=1; $b=5; f1();
    [1] => $aa = "aa"; function f4(){ /*...*/ }; $b=1; f4();
    [2] => $aa = "aa"; function f6(){ /*...*/ }; $b=1; f6();
)

或使用preg_match_all的较短变体:

$lines = file_get_contents('test.txt');
preg_match_all('/^.*?\bfunction\h+(\w+\([^()]*\)).*\1;/m', $lines, $m);
print_r($m[0]);

推荐阅读