I have this code which does good job at finding words but it does not join up the results. I need to replace the whole found phrase with something.
$needle = "pretty blue day";
$haystack = "
It was blue and pretty day yesterday
";
// explode into words
$hwords = preg_split("/[\s\W]+/", $haystack);
$nwords = preg_split("/[\s\W]+/", $needle);
echo "Haystack: <br>$haystack<br><br>You searched for $needle<br>";
echo "I found...<br>";
foreach ($hwords as $hkey => $hayword) {
$hmp = metaphone ($hayword);
foreach ($nwords as $nkey => $needword) {
// First or last letters of needle and haystack have to match (case insensitive)
$nfirst = strtolower(substr($needword, 0, 1));
$nlast = strtolower(substr($needword, -1));
$hfirst = strtolower(substr($hayword, 0, 1));
$hlast = strtolower(substr($hayword, -1));
if (($hfirst == $nfirst) or ($hlast == $nlast)) {
$nmp = metaphone ($needword);
$distance = levenshtein ($hmp, $nmp);
// $distance = levenshtein ($hayword, $needword);
$n_len = strlen($nmp);
$per = round(($distance/$n_len)*1000);
if ($per < 335) {
// Highlight word in haystack
$haystack = str_replace($hayword, "<b>$hayword</b>", $haystack);
$haystack = str_replace("<b><b>", "<b>", $haystack);
$haystack = str_replace("</b></b>", "</b>", $haystack);
}
}
}
}
// echo the new haystack
echo $haystack;