php - 如何在 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();
你能帮我吗?谢谢!!
解决方案
一种选择可能是使用
\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]);
推荐阅读
- paypal - 我想验证给定的电子邮件地址是否存在于贝宝中?我需要验证他们提供给我的贝宝电子邮件是否存在?
- go - Yaml 文件在 Golang 中进行结构解析(翻译)
- mysql - 为什么left()返回0,而substring()不返回
- tfs - 如何查询我在@tagged 中提到的 TFS 票证?
- maximo - MAXIMO 是否支持 SAML 身份验证
- php - PHP cURL 如何发送 JSON POST 请求并包含 URL 查询字符串?
- linux - 如何使用多阶段构建来消除 /go/pkg 文件
- laravel - Authorize.Net 订阅使用 CustomerProfileId 错误 E00121 Laravel PHP
- regex - 匹配失败时不返回正则表达式?
- excel - 在两个相同字符之间查找文本并更改其字体颜色