user984976
user984976

Reputation: 1334

preg_grep multiple words without order

I am attempting to search an array using preg_grep for any values which contain all the words listed in my pattern, in any order.

Assuming the words I want to search for are as follows: apple pear banana

I have tried:

$result = preg_grep("/(apple|pear|banana)/i", $array);

Which returns strings that contain any of the three words

$result = preg_grep("/(apple.*pear.*banana)/i", $array);

Which returns strings that contain all 3, but they must be in order.

How to perform unordered preg_grep?

Upvotes: 2

Views: 1619

Answers (2)

dshu610
dshu610

Reputation: 191

you can also try using a look ahead pattern..

preg_grep("/(?=.*apple)(?=.*pear)(?=.*banana).*/",$array);

Upvotes: 3

Barmar
Barmar

Reputation: 781350

Doing a "match all" in a single regexp is difficult -- you need to enumerate all possible orders, which is O(n!). Instead, use array_filter():

array_filter($array, function($x) {
    return preg_match('/apple/', $x) && preg_match('/pear/', $x) && preg_match('/banana/', $x);
});

Upvotes: 4

Related Questions