preg_match 显示包含一个字符串和另外两个字符串之一的行
preg_match to show lines containing one string and one of the other two
我在 php 中有一个数组:
Array
(
[0] => sth!Man!Tree!null
[1] => sth!Maning!AppTree!null
[2] => sth!Man!Lake!null
[3] => sth!Man!Tree!null
[4] => sth!Man!AppTree!null
[5] => sth!Maning!AppTree!null
[6] => sth!Man!Tree!null
[7] => sth!Maning!AppTree!null
[8] => sth!Maning!AppTree!null
[9] => sth!Man!Tree!null
[10] => sth!Man!Tree!null
[11] => sth!Man!Tree!null
[12] => sth!Man!Tree!null
[12] => sth!Man!Lake!null
[13] => sth!Maning!Tree!null
)
和这个 preg_match 函数:
preg_match("/Man/i", $line) && (preg_match("/!Tree!/i", $line) || preg_match("/!Lake!/i", $line))
我的目标是将其更改为一个 preg_match 正则表达式函数以仅显示包含 Man and Tree 或 Man and Lake 的线条。可能吗?
preg_match("/Man!(?:Tree|Lake)/i", $line, $matches)
应该最有效。
您可以使用以下正则表达式:
(?i)\b(?:Lake|Tree)\b.*\bMan\b|\bMan\b.*\b(?:Tree|Lake)\b
见demo。
单词边界只匹配整个单词,(?i)
内联模式选项启用不区分大小写的搜索,我们至少需要两个主要替代方案来解决Man
和[=的不同位置14=]/Tree
.
示例代码:
$re = "/(?i)\b(?:Lake|Tree)\b.*\bMan\b|\bMan\b.*\b(?:Tree|Lake)\b/";
$str = " Man and Tree or Man and Lake. Is it possible?";
preg_match($re, $str, $matches);
我在 php 中有一个数组:
Array
(
[0] => sth!Man!Tree!null
[1] => sth!Maning!AppTree!null
[2] => sth!Man!Lake!null
[3] => sth!Man!Tree!null
[4] => sth!Man!AppTree!null
[5] => sth!Maning!AppTree!null
[6] => sth!Man!Tree!null
[7] => sth!Maning!AppTree!null
[8] => sth!Maning!AppTree!null
[9] => sth!Man!Tree!null
[10] => sth!Man!Tree!null
[11] => sth!Man!Tree!null
[12] => sth!Man!Tree!null
[12] => sth!Man!Lake!null
[13] => sth!Maning!Tree!null
)
和这个 preg_match 函数:
preg_match("/Man/i", $line) && (preg_match("/!Tree!/i", $line) || preg_match("/!Lake!/i", $line))
我的目标是将其更改为一个 preg_match 正则表达式函数以仅显示包含 Man and Tree 或 Man and Lake 的线条。可能吗?
preg_match("/Man!(?:Tree|Lake)/i", $line, $matches)
应该最有效。
您可以使用以下正则表达式:
(?i)\b(?:Lake|Tree)\b.*\bMan\b|\bMan\b.*\b(?:Tree|Lake)\b
见demo。
单词边界只匹配整个单词,(?i)
内联模式选项启用不区分大小写的搜索,我们至少需要两个主要替代方案来解决Man
和[=的不同位置14=]/Tree
.
示例代码:
$re = "/(?i)\b(?:Lake|Tree)\b.*\bMan\b|\bMan\b.*\b(?:Tree|Lake)\b/";
$str = " Man and Tree or Man and Lake. Is it possible?";
preg_match($re, $str, $matches);