用于匹配查询字符串中的模式的正则表达式

RegEx for matching a pattern in query strings

我有一些代码可以创建查询字符串并循环检查查询字符串。

$pi = An ip defined
$bo = The content of a file.

我正在 $bo 中搜索并寻找 $pi 并且我想打印出与该字符串匹配的所有行但是我在打印出 $pi 中的某些行时遇到了一些问题=12=].

这是 $bo 中包含的内容:

if (strstr($bo, $pi)) {
    echo "<tr>";
    echo "<td>" . preg_match($ip, $body) . "</td>";
    echo "</tr>";
    $count++;
}

这是一个通用模式,您可以将其用于包含 $ip 字符串的整行:

$pattern = '/^.*\b' . $ip . '\b.*$/m';

然后,我们可以将此模式与 preg_match_all 结合使用来查找所有匹配行:

preg_match_all($pattern, $body, $matches);
print_r($matches[0]);

我会使用 preg_grep() 而不是 preg_match() 因为它直接 returns 只匹配并且不需要构建模式来捕获行。但是,它确实要求输入是文件中的行数组,您可以通过 file()explode():

轻松完成
// Read a file directly into an array.
$body = file('/path/to/file');

// Or split an existing big string into an array of lines.
$body = explode("\n", $fileContents);

foreach (preg_grep($ip, $body) as $line) {
    echo $line;
}

或者只是:

echo implode("\n", preg_grep($ip, $body));