Jump to content

Advanced Search


AudiS2

Recommended Posts

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.