Reputation: 73
How can I find if my string contain multiple word by specific order for example:
$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);
I need $res1
will be true
and $res2
will be false
.
I am trying preg_match_all
but it always return true
.
NOTE: I am work with hebrew characters.
Upvotes: 1
Views: 83
Reputation: 68526
The function takes an array and your actual string as input. Using a foreach
the position of the matched keywords are recorded in an array. After the end of the loop , we have another array which takes the value of this array(positions) and does a sort
. Now the validity and invalidity check depends on whether if the sorted values of array matches with the values that was initially got from the loop. If both are same , then we raise a VALID
flag , if not an INVALID
flag.
<?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
Upvotes: 0
Reputation: 1430
Not too nice option, but as a quick fix go:
$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;
}
Upvotes: 1
Reputation: 91438
Here is a way to go:
$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);
}
output:
1
0
Upvotes: 1