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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.