AudiS2 Posted July 18, 2008 Share Posted July 18, 2008 Task: Replace a string using advanced matching Example: $needle="pretty blue day" $haystack="It was blue and pretty day yesterday" Match "blue and pretty day", meaning the $needle can be permuted and additional words can be inserted in between (one or two words max, if possible this would be a setting). Quote Link to comment Share on other sites More sharing options...
samshel Posted July 18, 2008 Share Posted July 18, 2008 did you already try something ? if yes, post some code please. Quote Link to comment Share on other sites More sharing options...
AudiS2 Posted July 19, 2008 Author Share Posted July 19, 2008 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; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.