Explanation :
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
Working Demo