在 PHP 中使用 preg_match 获取带有我的模式字符串的那一行之后的行
Use preg_match in PHP to get the line after the one with my pattern string
我正在使用以下脚本从文本文件中获取特定行:
$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";
}
这很好用,但我现在想做的也是在我的 matches() 数组中包含每个匹配项的下一行。
例如,如果我的文本文件如下所示:
Address to be geocoded:....
Other line 1
Other line 2
Address to be geocoded: ...
Other line x
Other line x2
我想获取带有 "Address to be geocoded:...." 的行加上以下行:其他行 1 和其他行 x。
是否可以使用正则表达式和preg_match?
您可以尝试类似的操作:
$pattern = "/^.*$pattern.*\n.*\n.*$/m";
它将匹配 -> 您搜索的元素 + 行尾 + 所有下一行
我正在使用以下脚本从文本文件中获取特定行:
$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";
}
这很好用,但我现在想做的也是在我的 matches() 数组中包含每个匹配项的下一行。 例如,如果我的文本文件如下所示:
Address to be geocoded:....
Other line 1
Other line 2
Address to be geocoded: ...
Other line x
Other line x2
我想获取带有 "Address to be geocoded:...." 的行加上以下行:其他行 1 和其他行 x。
是否可以使用正则表达式和preg_match?
您可以尝试类似的操作:
$pattern = "/^.*$pattern.*\n.*\n.*$/m";
它将匹配 -> 您搜索的元素 + 行尾 + 所有下一行