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

元气小坏坏 提交于 2019-12-02 09:09:55

问题


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?


回答1:


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

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



回答2:


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";
}


来源:https://stackoverflow.com/questions/15120472/php-preg-match-matching-when-2-words-might-come-in-random-sequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!