Home > Back-end >  How can I also echo the next line with regex?
How can I also echo the next line with regex?

Time:10-04

I am using the code below to find specific text and then echo the whole line. However, I want it to also echo the line below it too.

Is that doable?

Thanks

$file = 'file.txt';
$searchfor = "$groupName";

$contents = file_get_contents($file);

$pattern = preg_quote($searchfor, '/');

$pattern = "/^.*$pattern.*\$/m";


if (preg_match_all($pattern, $contents, $matches)){
    echo implode("\n", $matches[0]);
}else{
    echo "No matches found for - $searchfor";
}

CodePudding user response:

You can match an optional next line with

$pattern = "/^.*$pattern.*(?:\R.*)?/m";

Details:

  • ^ - start of a line
  • .* - any zero or more chars other than line break chars as many as possible
  • $pattern - the defined $pattern
  • .* - any zero or more chars other than line break chars as many as possible
  • (?:\R.*)? - an optional sequence of any line break sequence and then any zero or more chars other than line break chars as many as possible.
  • Related