3

Im using the preg_match to find a certain word in a text file. However, I want to define the starting line from which preg_match starts its search. How can I make preg_match to ignore the first 5 lines? Additionally, I have a code which will automatically delete the preg_matched word from the file, so im not sure a "start from keyword" would work here.

Heres the code im using.

$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/\b$pattern\b/m";
if(preg_match_all($pattern, $contents, $matches))
BenMorel
  • 34,448
  • 50
  • 182
  • 322
A. McMount
  • 141
  • 6

3 Answers3

2

Prefixing your pattern with

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

should discard the first 5 rows of any search please see the demo below

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

Your code would then look like this

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

I would go this way, like @JustOnUnderMillions suggested

$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
LiTe
  • 166
  • 1
  • 1
  • 8
0

If you want to ignore the first 5 lines then

"/^(?:.*?\n){5,5}[^\n]/"

should do it.

https://regex101.com/r/TEBTYt/1

GordonM
  • 31,179
  • 15
  • 87
  • 129