Search code examples
phppreg-match

Use preg_match in PHP to get the line after the one with my pattern string


I am using the following script in order to get specific lines from a text file:

$searchfor = "Address to be geocoded";
// get the file contents
$contents = file_get_contents('predictVdslEligibilityWSLog-20150614.txt');
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";

// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
  echo "Found matches:\n";
  echo implode("\n", $matches[0]);
}
else{
  echo "No matches found";
}

This works fine but what I want to do now is also to include in my matches() array also the very next line of each matching. For example if my text file looks like this:

Address to be geocoded:....
Other line 1
Other line 2
Address to be geocoded: ...
Other line x
Other line x2

I want to get the lines with "Address to be geocoded:...." PLUS the lines: Other line 1 AND Other line x.

Is this possible using regular expressions and preg_match?


Solution

  • You can try something like that : $pattern = "/^.*$pattern.*\n.*\n.*\$/m"; It will match with -> the element your search + the end of the line + the all next line