Kristian Rafteseth
Kristian Rafteseth

Reputation: 2032

php preg_match, matching when 2 words might come in random sequence

Is it possible to match two words that might come in random sequences? Examples:

$title = "2 pcs watch for couple";
$title = "couple watch 2 pcs";

Currently I'm using two regexes:

if (preg_match("/2( )?pcs/i", $title) and preg_match("/couple/i", $title))

Just want to know if it can be done with only 1?

Upvotes: 1

Views: 2016

Answers (2)

MikeM
MikeM

Reputation: 13641

If you're just testing for the presence of the two words in the string you could use

'/couple.*2 pcs|2 pcs.*couple/' 

Upvotes: 2

user1646111
user1646111

Reputation:

use strpos()

if(strpos($string, '2 pcs') !== False){
 //its found
}

or matching at first and at end

if(preg_match("/(^(2 pcs|couples)|(2 pcs|couples)$)/", '2 pcs watch for couples')){
//echo "found";
}

or

Matching anywhere:

if(preg_match("/(2 pcs|couples)/", '2 pcs watch for couples')){
//echo "found";
}

Upvotes: 1

Related Questions