gpt4 book ai didi

php - 如何在 PHP 中定义 preg_match 的起始行?

转载 作者:行者123 更新时间:2023-12-05 05:21:16 26 4
gpt4 key购买 nike

我正在使用 preg_match 在文本文件中查找特定单词。但是,我想定义 preg_match 开始搜索的起始行。如何让 preg_match 忽略前 5 行?此外,我有一个代码会自动从文件中删除 preg_matched 词,所以我不确定“从关键字开始”在这里是否有效。

这是我使用的代码。

$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/\b$pattern\b/m";
if(preg_match_all($pattern, $contents, $matches))

最佳答案

为你的模式加上前缀

^((.*)\n){5}\K

应该丢弃任何搜索的前 5 行,请参见下面的演示

https://regex101.com/r/wFqazl/2

你的代码看起来像这样

$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^((.*)\n){5}\K\b$pattern\b/m";
if(preg_match_all($pattern, $contents, $matches))

关于php - 如何在 PHP 中定义 preg_match 的起始行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43257591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com