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). Link to comment https://forums.phpfreaks.com/topic/115398-advanced-search/ 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. Link to comment https://forums.phpfreaks.com/topic/115398-advanced-search/#findComment-593278 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; Link to comment https://forums.phpfreaks.com/topic/115398-advanced-search/#findComment-594325 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.