好吧,我想说我想在一个句子中匹配3个单词......但是我要按任意顺序匹配它们,例如:
$sentences = Array(
"one two three four five six seven eight nine ten",
"ten nine eight seven six five four three two one",
"one three five seven nine ten",
"two four six eight ten",
"two ten four six one",
);
所以我需要匹配单词" two"," four" &安培; "十",但是以任何顺序,他们可以或不可以在他们之间有任何其他的话。我试试
foreach($sentences AS $sentence) {
$n++;
if(preg_match("/(two)(.*)(four)(.*)(ten)/",$sentence)) {
echo $n." matched\n";
}
}
但这只会匹配句子1,我需要匹配句子1,2,4& 5。
我希望你能帮忙...... 问候! (对不起我的英语)
答案 0 :(得分:4)
您可以使用积极前瞻来实现这一目标。
前瞻方法非常适合匹配包含这些子串的字符串而不管顺序。
if (preg_match('/(?=.*two)(?=.*four)(?=.*ten)/', $sentence)) {
echo $n." matched\n";
}