如何查找我的字符串是否按特定顺序包含多个单词 例如:
$str="(can be any more words here). This is my search string. (can be any more word here).";
$words1 = array("is", "search");
$words2 = array("search", "is");
$res1 = findMe($str, $words1);
$res2 = findMe($str, $words2);
我需要$res1
true
而$res2
将是false
。
我正在尝试preg_match_all
,但它总是返回true
。
注意:我使用希伯来语字符。
答案 0 :(得分:1)
不是太好的选择,但作为快速解决方法:
$str="(can any more words here). This is my search string. (can be any more word here).";
$words1 = array("be", "is", "search");
$words2 = array("search", "is");
$words3 = array("is", "search");
$res1 = findMe($str, $words1);
$res2 = findMe($str, $words2);
$res3 = findMe($str, $words3);
var_dump($res1);
var_dump($res2);
var_dump($res3);
function findMe($str, $words){
$prevs = 0;
foreach($words as $word){
$n = strpos($str, $word);
if($n!==false&&$prevs<=$n)
$prevs = $n;
else
return false;
}
return true;
}
答案 1 :(得分:1)
这是一种方法:
$str="(can be any more words here). This is my search string. (can be any more word here).";
$words1 = array("is", "search");
$words2 = array("search", "is");
echo findMe($str, $words1), "\n";
echo findMe($str, $words2), "\n";
function findMe($str, $words) {
$pat = '/\b'.implode($words, '\b.*?\b') .'\b/';
return preg_match($pat, $str);
}
<强>输出:强>
1
0
答案 2 :(得分:0)
该函数将数组和您的实际字符串作为输入。使用foreach
匹配关键字的位置记录在数组中。循环结束后,我们有另一个数组,它取这个数组的值(位置)并执行sort
。现在,有效性和无效性检查取决于数组的排序值是否与最初从循环中获得的值匹配。如果两者都相同,那么我们会引发VALID
标志,如果不是INVALID
标志。
<?php
$str="(can be any more words here). This is my search string. (can be any more word here).";
$words1 = array("is", "search");
$words2 = array("search", "is");
function findMe($arr,$str)
{
$new_arr = array_map(function ($v) use ($str){ return mb_strpos($str,$v);},$arr);
$sorted = array_values($new_arr);
sort($sorted,SORT_ASC);
return ($new_arr === $sorted)? "VALID" : "INVALID";
}
echo findMe($words1,$str); //prints VALID
echo findMe($words2,$str); //prints INVALID