php preg_匹配,当两个单词可能以随机顺序出现时匹配
是否有可能匹配两个可能以随机顺序出现的单词? 示例:php preg_匹配,当两个单词可能以随机顺序出现时匹配,php,regex,preg-match,Php,Regex,Preg Match,是否有可能匹配两个可能以随机顺序出现的单词? 示例: $title = "2 pcs watch for couple"; $title = "couple watch 2 pcs"; 目前我使用两个正则表达式: if (preg_match("/2( )?pcs/i", $title) and preg_match("/couple/i", $title)) 只想知道是否只需要1个就可以完成吗?使用strpos() 或者在开头和结尾匹配 if(preg_match("/(^(2 pcs|c
$title = "2 pcs watch for couple";
$title = "couple watch 2 pcs";
目前我使用两个正则表达式:
if (preg_match("/2( )?pcs/i", $title) and preg_match("/couple/i", $title))
只想知道是否只需要1个就可以完成吗?使用strpos()
或者在开头和结尾匹配
if(preg_match("/(^(2 pcs|couples)|(2 pcs|couples)$)/", '2 pcs watch for couples')){
//echo "found";
}
或
在任何地方匹配:
if(preg_match("/(2 pcs|couples)/", '2 pcs watch for couples')){
//echo "found";
}
如果您只是测试字符串中是否存在这两个单词,那么可以使用
'/couple.*2 pcs|2 pcs.*couple/'
为什么它必须是正则表达式?而且,第一个字符串与整个单词的“couple”不匹配。这个例子好吗?你是说我不能用一个正则表达式同时匹配两个正则表达式,我需要使用2个正则表达式吗?@SamDufel你说的更高效是什么意思?我认为
if(preg_-match('/couple.*2()?pcs | 2()?pcs.*couple/',$string))
看起来比if((stripos('title,'2pcs')或stripos('title,'2pcs'))和stripos('title,'couple'))更好。
@KristianRafteseth-正则表达式匹配比基本字符串匹配需要更多的处理能力。
'/couple.*2 pcs|2 pcs.*couple/'