Driver
Driver

Reputation: 199

preg_match to show lines containing one string and one of the other two

I've got an array in 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
)

and this preg_match function:

preg_match("/Man/i", $line) && (preg_match("/!Tree!/i", $line) || preg_match("/!Lake!/i", $line))

My goal is to change it to one preg_match regex function to display only lines with Man and Tree or Man and Lake. Is it possible?

Upvotes: 2

Views: 359

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

You can use the following regex:

(?i)\b(?:Lake|Tree)\b.*\bMan\b|\bMan\b.*\b(?:Tree|Lake)\b

See demo.

The word boundaries match only the whole words, (?i) inline mode option enables case-insensitive search, and we need at least two main alternatives to account for different positions of Man and Lake/Tree.

Sample code:

$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);

Upvotes: 2

Chris Brendel
Chris Brendel

Reputation: 700

preg_match("/Man!(?:Tree|Lake)/i", $line, $matches) should do it most efficiently.

Upvotes: 1

Related Questions