如何在PHP中定义preg_match的起点?

如何在PHP中定义preg_match的起点?,php,preg-match-all,Php,Preg Match All,我使用preg_匹配在文本文件中查找某个单词。但是,我想定义preg_match开始搜索的起始线。如何使preg_匹配忽略前5行? 此外,我有一个代码将自动删除preg_匹配的字从文件中,所以我不确定一个“开始从关键字”将在这里工作 这是我使用的代码 $contents = file_get_contents($file); $pattern = preg_quote($searchfor, '/'); $pattern = "/\b$pattern\b/m"; if(preg_match_al

我使用preg_匹配在文本文件中查找某个单词。但是,我想定义preg_match开始搜索的起始线。如何使preg_匹配忽略前5行? 此外,我有一个代码将自动删除preg_匹配的字从文件中,所以我不确定一个“开始从关键字”将在这里工作

这是我使用的代码

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

我会走这条路,就像@JustOnUnderMillions建议的那样

$input = file($file);
$output = array_slice($input, 5); // cut off first 5 lines
$output = implode("\n", $output); // join left lines into one string

// do your preg_* functions on output

在模式前面加上前缀

^((.*)\n){5}\K
如果要放弃任何搜索的前5行,请参阅下面的演示

您的代码将如下所示

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

如果要忽略前5行,则

"/^(?:.*?\n){5,5}[^\n]/"
我应该这样做

最好使用
file()
获取一个数组,每行作为一个条目,然后在索引5上执行正则表达式(忽略前5行)。