If you think about optimization there a lot of pattern search algorithms
Here is sample of naive pattern search:
/**
* Naive algorithm for Pattern Searching
*/
function search(string $pat, string $txt, int $searchFrom = 0, ?int $searchTill = null)
{
$M = strlen($pat);
$N = strlen($txt);
if ($searchTill !== null && $searchTill < $N){
$N = $searchTill;
}
for ($i = $searchFrom; $i <= $N - $M; $i++)
{
// For current index i,
// check for pattern match
for ($j = 0; $j < $M; $j++)
if ($txt[$i + $j] != $pat[$j])
break;
// if pat[0...M-1] =
// txt[i, i+1, ...i+M-1]
if ($j == $M)
return $i;
}
}
// Driver Code
$txt = "BaaaaBcccccHELLOcccccBaaaaB";
if (null!==($helloPos = search("HELLO", $txt))){
print("First Occurance of B before Hello is ".search("B", $txt, 0, $helloPos)."<br>") ;
print("First Occurance of B after Hello is ".search("B", $txt, $helloPos, null)."<br>") ;
}