예제 #1
1
 public function closest($input, array $words)
 {
     // no shortest distance found, yet
     $shortest = -1;
     $match = [];
     // loop through words to find the closest
     foreach ($words as $word) {
         // calculate the distance between the input word,
         // and the current word
         $lev = levenshtein(strtolower($input), strtolower($word), 1, 2, 3);
         // check for an exact match
         if ($lev == 0) {
             // closest word is this one (exact match)
             $match = [$word];
             // $closest = $word;
             $shortest = 0;
             // break out of the loop; we've found an exact match
             break;
         }
         // if this distance is less than the next found shortest
         // distance, OR if a next shortest word has not yet been found
         if ($lev < $shortest || $shortest < 0) {
             // set the closest match, and shortest distance
             $match = [$word];
             // $closest = $word;
             $shortest = $lev;
         } elseif ($lev == $shortest) {
             $match[] = $word;
         }
     }
     if ($shortest > 6) {
         return [];
     }
     return $match;
 }
예제 #2
0
 public function process(ContainerBuilder $container)
 {
     $compiler = $container->getCompiler();
     $formatter = $compiler->getLoggingFormatter();
     $tags = array_unique(array_merge($container->findTags(), $this->whitelist));
     foreach ($container->findUnusedTags() as $tag) {
         // skip whitelisted tags
         if (in_array($tag, $this->whitelist)) {
             continue;
         }
         // check for typos
         $candidates = array();
         foreach ($tags as $definedTag) {
             if ($definedTag === $tag) {
                 continue;
             }
             if (false !== strpos($definedTag, $tag) || levenshtein($tag, $definedTag) <= strlen($tag) / 3) {
                 $candidates[] = $definedTag;
             }
         }
         $services = array_keys($container->findTaggedServiceIds($tag));
         $message = sprintf('Tag "%s" was defined on service(s) "%s", but was never used.', $tag, implode('", "', $services));
         if (!empty($candidates)) {
             $message .= sprintf(' Did you mean "%s"?', implode('", "', $candidates));
         }
         $compiler->addLogMessage($formatter->format($this, $message));
     }
 }
예제 #3
0
 function compare($debug = false)
 {
     $first = $this->str1;
     $second = $this->str2;
     $this->levenshtein = levenshtein($first, $second);
     $this->similarity['value'] = $sim = similar_text($first, $second, $perc);
     $this->similarity['percentage'] = $perc;
     if ($debug) {
         echo "{$first} | {$second}<br>";
         echo "leven: " . $this->levenshtein;
         echo '<br>similarity: ' . $sim . ', ' . $perc . '%<br><br>';
     }
     $soundex1 = soundex($first);
     $soundex2 = soundex($second);
     $this->soundex['levenshtein'] = levenshtein($soundex1, $soundex2);
     $this->soundex['similarity'] = $sim = similar_text($soundex1, $soundex2, $perc);
     $this->soundex['percentage'] = $perc;
     if ($debug) {
         echo "Soundex: " . $soundex1 . ", " . $soundex2 . "<BR>";
         echo 'levenshtein: ' . $this->soundex['levenshtein'] . '<br>';
         echo 'similarity: ' . $sim . ', ' . $perc . '%<br><br>';
     }
     $m1 = metaphone($first);
     $m2 = metaphone($second);
     $this->metaphone['levenshtein'] = levenshtein($m1, $m2);
     $this->metaphone['similarity'] = $sim = similar_text($m1, $m2, $perc);
     $this->metaphone['percentage'] = $perc;
     if ($debug) {
         echo "metaphone: " . $m1 . ", " . $m2 . "<br>";
         echo 'levenshtein: ' . $this->metaphone['levenshtein'] . '<br>';
         echo 'similarity: ' . $sim . ', ' . $perc . '%<br>';
         echo '<br>-------------------<br>';
     }
 }
예제 #4
0
function findClosest1($input = 0, $numbers)
{
    // array of numbers to check
    sort($numbers);
    // no shortest distance found, yet
    $shortest = -1;
    // loop through numbers to find the closest
    foreach ($numbers as $num) {
        // calculate the distance between the input num,
        // and the current num
        $lev = levenshtein($input, $num);
        // check for an exact match
        if ($lev == 0) {
            // closest num is this one (exact match)
            $closest = $num;
            $shortest = 0;
            // break out of the loop; we've found an exact match
            break;
        }
        // if this distance is less than the next found shortest
        // distance, OR if a next shortest num has not yet been found
        if ($lev <= $shortest || $shortest < 0) {
            // set the closest match, and shortest distance
            $closest = $num;
            $shortest = $lev;
        }
    }
    echo "Closest number is: " . $closest;
}
예제 #5
0
 private function levenshteinDistance($input, $words)
 {
     $shortest = -1;
     $closest = [];
     foreach ($words as $key => $word) {
         $lev = levenshtein($input, explode(' ', $word)[0]);
         if ($lev == 0 && count(explode(' ', $word)) == 1) {
             return $word;
         }
         if ($lev <= $shortest || $shortest < 0) {
             $closest[] = [$word, $lev, $key];
             $shortest = $lev;
         }
     }
     $top4 = array_slice(array_reverse($closest), 0, 3);
     foreach ($top4 as $key => $item) {
         if ($item[1] > 3) {
             unset($top4[$key]);
         }
     }
     if (count($top4) == 1) {
         return reset($top4)[0];
     }
     return count($top4) > 0 ? $top4 : false;
 }
예제 #6
0
function edicao($string, &$strings, &$resultado)
{
    $sql = "SELECT DISTINCT texto FROM T_PALAVRA_CHAVE";
    $result = mysql_query($sql);
    $i = 0;
    while ($row = mysql_fetch_array($result)) {
        $word = $row['texto'];
        $r = levenshtein($string, $word);
        if ($i < 5) {
            $strings[$i] = $word;
            $resultado[$i] = $r;
            $i = $i + 1;
            ordenarVetor($strings, $resultado, $i);
        } else {
            if ($r < $resultado[4]) {
                $strings[4] = $word;
                $resultado[4] = $r;
                ordenarVetor($strings, $resultado, 5);
            }
        }
    }
    $tamanho = strlen($string);
    for ($i = 0; $i < 5; $i++) {
        if (2 * $resultado[$i] > max($tamanho, strlen($strings[$i]))) {
            $strings[$i] = "";
        }
    }
}
예제 #7
0
 public function match($input)
 {
     // no shortest distance found, yet
     $shortest = -1;
     // loop through words to find the closest
     foreach ($this->possibleTokens as $word) {
         // calculate the distance between the input word,
         // and the current word
         $lev = levenshtein($input, $word);
         // check for an exact match
         if ($lev == 0) {
             // closest word is this one (exact match)
             $closest = $word;
             $shortest = 0;
             // break out of the loop; we've found an exact match
             break;
         }
         // if this distance is less than the next found shortest
         // distance, OR if a next shortest word has not yet been found
         if ($lev <= $shortest || $shortest < 0) {
             // set the closest match, and shortest distance
             $closest = $word;
             $shortest = $lev;
         }
     }
     return $closet;
 }
예제 #8
0
 /**
  *
  * @param string $word
  * @param array $words
  * @return array
  */
 public static function similarWord($word, array $words)
 {
     $similarity = config('pages.similar.similarity');
     $metaSimilarity = 0;
     $minLevenshtein = 1000;
     $metaMinLevenshtein = 1000;
     $result = [];
     $metaResult = [];
     foreach ($words as $n) {
         $minLevenshtein = min($minLevenshtein, levenshtein($n, $word));
     }
     foreach ($words as $n => $k) {
         if (levenshtein($k, $word) <= $minLevenshtein) {
             if (similar_text($k, $word) >= $similarity) {
                 $result[$n] = $k;
             }
         }
     }
     foreach ($result as $n) {
         $metaMinLevenshtein = min($metaMinLevenshtein, levenshtein(metaphone($n), metaphone($word)));
     }
     foreach ($result as $n) {
         if (levenshtein($n, $word) == $metaMinLevenshtein) {
             $metaSimilarity = max($metaSimilarity, similar_text(metaphone($n), metaphone($word)));
         }
     }
     foreach ($result as $n => $k) {
         if (levenshtein(metaphone($k), metaphone($word)) <= $metaMinLevenshtein) {
             if (similar_text(metaphone($k), metaphone($word)) >= $metaSimilarity) {
                 $metaResult[$n] = $k;
             }
         }
     }
     return $metaResult;
 }
예제 #9
0
 function find_similar_words($word, $threshold)
 {
     $similar = array();
     $word = addslashes(trim($word));
     $sndx = substr($word, 0, 2);
     $query = "select `word` from `{$this->tbl}` where `di`=?";
     @($result = $this->query($query, array($sndx)));
     while ($res = $result->fetchRow(DB_FETCHMODE_ASSOC)) {
         $tword = $res["word"];
         $lev = levenshtein($tword, $word);
         if (count($similar) < $threshold) {
             $similar[$tword] = $lev;
             asort($similar);
         } else {
             // If the array is full then if the lev is better than the worst lev
             // then update
             $keys = array_keys($similar);
             $last_key = $keys[count($keys) - 1];
             if ($lev < $similar[$last_key]) {
                 unset($similar[$last_key]);
                 $similar[$tword] = $lev;
                 asort($similar);
             }
         }
     }
     return $similar;
 }
 /**
  * handler for 404 (page not found) error
  *
  * @param string $sUrl url which was given, can be not specified in some cases
  *
  * @return void
  */
 public function handlePageNotFoundError($sUrl = '')
 {
     // module active?
     if (!oxRegistry::getConfig()->getConfigParam("psRedirect404_status")) {
         return parent::handlePageNotFoundError($sUrl = '');
     }
     $iShortest = -1;
     $iHeaderType = 302;
     $sSearchString = $this->_clearUrl($sUrl);
     // psRedirect404
     // checks based on levenshtein algorithm closest url from
     // oxid seo urls (oxseo) and redirect with header 302 to this page
     try {
         foreach ($this->_getSeoUrls() as $value) {
             $sUrl = $this->_clearUrl($value[0]);
             $sLevRes = levenshtein($sSearchString, $sUrl);
             #echo $sLevRes." - ".$sUrl." (".$value[0].")<br>";
             if ($sLevRes <= $iShortest || $iShortest < 0) {
                 $sClosest = $value[0];
                 $iShortest = $sLevRes;
                 if ($sLevRes <= 10 && oxRegistry::getConfig()->getConfigParam("psRedirect404_redirecttype") == "auto") {
                     $iHeaderType = 301;
                 }
             }
         }
         if (!oxRegistry::getConfig()->getConfigParam("psRedirect404_redirecttype") == "301") {
             $iHeaderType = 301;
         }
         oxRegistry::getUtils()->redirect(oxRegistry::getConfig()->getShopUrl() . $sClosest, false, $iHeaderType);
     } catch (Exception $e) {
     }
     $this->showMessageAndExit("Found");
 }
 public function correct($word, $dictionary)
 {
     if (strlen($word) < 255) {
         $word = strtolower($word);
         if (isset($dictionary[$word])) {
             return $word;
         }
         $edits1 = $edits2 = array();
         foreach ($dictionary as $dictWord => $count) {
             $dist = levenshtein($word, $dictWord);
             if ($dist == 1) {
                 $edits1[$dictWord] = $count;
             } else {
                 if ($dist == 2) {
                     $edits2[$dictWord] = $count;
                 }
             }
         }
         if (count($edits1)) {
             arsort($edits1);
             return key($edits1);
         } else {
             if (count($edits2)) {
                 arsort($edits2);
                 return key($edits2);
             }
         }
     } else {
         $word = '';
     }
     return $word;
 }
function MakeSuggestion($keyword, $ln)
{
    $trigrams = BuildTrigrams($keyword);
    $query = "\"{$trigrams}\"/1";
    $len = strlen($keyword);
    $delta = LENGTH_THRESHOLD;
    $weight = 'weight()';
    if (SPHINX_20 == true) {
        $weight = '@weight';
    }
    $stmt = $ln->prepare("SELECT *, {$weight} as w, w+:delta-ABS(len-:len) as myrank FROM suggest WHERE MATCH(:match) AND len BETWEEN :lowlen AND :highlen\r\n\t\t\tORDER BY myrank DESC, freq DESC\r\n\t\t\tLIMIT 0,:topcount OPTION ranker=wordcount");
    $stmt->bindValue(':match', $query, PDO::PARAM_STR);
    $stmt->bindValue(':len', $len, PDO::PARAM_INT);
    $stmt->bindValue(':delta', $delta, PDO::PARAM_INT);
    $stmt->bindValue(':lowlen', $len - $delta, PDO::PARAM_INT);
    $stmt->bindValue(':highlen', $len + $delta, PDO::PARAM_INT);
    $stmt->bindValue(':topcount', TOP_COUNT, PDO::PARAM_INT);
    $stmt->execute();
    if (!($rows = $stmt->fetchAll())) {
        return false;
    }
    // further restrict trigram matches with a sane Levenshtein distance limit
    foreach ($rows as $match) {
        $suggested = $match["keyword"];
        if (levenshtein($keyword, $suggested) <= LEVENSHTEIN_THRESHOLD) {
            return $suggested;
        }
    }
    return $keyword;
}
예제 #13
0
파일: PHPcheck.php 프로젝트: Ponnaka/projet
function correct_word($mot, $dictionnaire)
{
    $mot_entre = strtolower($mot);
    if (in_array($mot_entre, $dictionnaire)) {
        $faute = false;
        $correction = false;
    } else {
        //Si le mot n'est pas dans le dictionnaire
        $distance = -1;
        //On va rechercher des distances de mots : pour l'instant, elle est à moins un.
        $suggestions = array();
        foreach ($dictionnaire as $mot_dico) {
            $lev = levenshtein($mot_entre, $mot_dico);
            if ($lev <= 2) {
                $faute = true;
                $correction = true;
                $suggestions[$lev] = $mot_dico;
            }
        }
        if (!isset($faute)) {
            //Si il n'existe aucun mot à correspondance exacte et si le mot est trop éloigné du dico
            $faute = true;
            $correction = false;
        }
    }
    if ($faute && $correction) {
        ksort($suggestions);
        $return = current($suggestions);
    } elseif ($faute && !$correction) {
        $return = $mot;
    } else {
        $return = $mot;
    }
    return $return;
}
function relevanssi_didyoumean($query, $pre, $post, $n = 5)
{
    global $wpdb, $relevanssi_variables, $wp_query;
    $total_results = $wp_query->found_posts;
    if ($total_results > $n) {
        return;
    }
    $q = "SELECT query, count(query) as c, AVG(hits) as a FROM " . $relevanssi_variables['log_table'] . " WHERE hits > 1 GROUP BY query ORDER BY count(query) DESC";
    $q = apply_filters('relevanssi_didyoumean_query', $q);
    $data = $wpdb->get_results($q);
    $distance = -1;
    $closest = "";
    foreach ($data as $row) {
        if ($row->c < 2) {
            break;
        }
        $lev = levenshtein($query, $row->query);
        if ($lev < $distance || $distance < 0) {
            if ($row->a > 0) {
                $distance = $lev;
                $closest = $row->query;
                if ($lev == 1) {
                    break;
                }
                // get the first with distance of 1 and go
            }
        }
    }
    if ($distance > 0) {
        $url = get_bloginfo('url');
        $url = esc_attr(add_query_arg(array('s' => urlencode($closest)), $url));
        $url = apply_filters('relevanssi_didyoumean_url', $url);
        echo "{$pre}<a href='{$url}'>{$closest}</a>{$post}";
    }
}
function output_remote_mfg_options($mfgs, $levenshtein = false, $id = false)
{
    $outputs = array();
    $copies = $mfgs;
    if (!empty($levenshtein)) {
        while (!empty($copies)) {
            $key = null;
            $distance = PHP_INT_MAX;
            foreach ($copies as $jj => $copy) {
                $lev = levenshtein($copy['mf_name'], $levenshtein);
                if ($lev < $distance) {
                    $key = $jj;
                    $distance = $lev;
                }
            }
            $outputs[] = $copies[$key];
            unset($copies[$key]);
            $copies = array_values($copies);
        }
    } else {
        $outputs = $mfgs;
    }
    //echo "<select name='maps' id="">";
    $c = 0;
    foreach ($outputs as $mfg) {
        $selected = '';
        if ($mfg['manufacturer_id'] == $id || $id === false && $c === 0) {
            $selected = " selected='selected'";
            $c += 1;
        }
        echo "<option value='{$mfg['manufacturer_id']}'{$selected}>{$mfg['mf_name']}</option>";
    }
    //echo "</select>";
}
예제 #16
0
 public static function get_link($movieId)
 {
     $link = self::find_by_id($movieId);
     $exists = $link ? true : false;
     if ($link && days_from_now($link->timestamp) < LINK_UPDATE_DAYS) {
         // good
     } else {
         $exists = $link ? true : false;
         $movie = Movie::find_by_id($movieId);
         $link = new YouTube();
         $link->id = $movieId;
         $link->timestamp = gen_timestamp();
         $title = urlencode($movie->title);
         $endpoint = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=10&q={$title}&type=video&videoCategoryId=30&key=AIzaSyBOaDIBNUCfbthPQ0XSZScnqI8jyxJ9G5Q";
         $m = self::getData($endpoint);
         foreach ($m->items as $mov) {
             $desc = $mov->snippet->description;
             if (levenshtein($title, $mov->snippet->title) < 2) {
                 foreach ($castArr as $actor) {
                     if (strpos($desc, $actor) !== false) {
                         $link->videoId = $mov->id->videoId;
                         break 2;
                         // break out of both foreach loops
                     }
                 }
             }
         }
         if ($exists) {
             $link->update();
         } else {
             $link->create();
         }
     }
     return $link;
 }
예제 #17
0
 function getDidyoumeanText()
 {
     Mage::getSingleton('catalogsearch/fulltext')->prepareResult();
     $search = Mage::getModel('catalogsearch/Mysql4_fulltext_collection');
     $search->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes());
     $search->loadData();
     $bestMatch = array();
     $input = Mage::helper('catalogsearch')->getQueryText();
     foreach ($search as $search1) {
         $words1 = explode(" ", $search1->getName());
         for ($k = 0; $k < count($words1); $k++) {
             $keyword = $words1[$k];
             $str1 = strtolower($keyword);
             $str2 = strtolower($input);
             $lev = levenshtein($str1, $str2, 1, 1, 1);
             if (isset($keyword) && trim($keyword) != "") {
                 $bestMatch[$lev][] = $keyword;
             }
             if (!isset($lowest) || $lev < $lowest) {
                 $lowest = $lev;
             }
         }
     }
     return array_unique($bestMatch[$lowest]);
 }
예제 #18
0
 public function match(&$collection, $needle, $tolerance)
 {
     $best = $tolerance;
     $match = '';
     $needle_chars = count_chars($needle);
     foreach ($collection as $userAgent) {
         $ua_chars = count_chars($userAgent);
         $sum = 0;
         $can_apply_ld = true;
         //Check from 32 (space) to 122 ('z')
         for ($i = 32; $i < 122; $i++) {
             $sum += abs($needle_chars[$i] - $ua_chars[$i]);
             if ($sum > 2 * $tolerance) {
                 $can_apply_ld = false;
                 break;
             }
         }
         if ($can_apply_ld === true) {
             $current = levenshtein($needle, $userAgent);
             if ($current <= $best) {
                 $best = $current - 1;
                 $match = $userAgent;
             }
         }
     }
     return $match;
 }
예제 #19
0
파일: main.php 프로젝트: rwos/scrapyard
function get_brain($input)
{
    global $knowledge;
    if (isset($knowledge[$input])) {
        return $knowledge[$input];
    } else {
        if (!empty($knowledge)) {
            // find lowest distance
            $best = '';
            $best_error = 1000000;
            // random high number
            foreach ($knowledge as $saved_in => $brain) {
                $error = levenshtein($saved_in, $input);
                if ($error < $best_error) {
                    $best_error = $error;
                    $best = $brain;
                }
                // is error == 0 --> return that
            }
            // TODO: if error < 1
            return $best;
            // TODO: else -> kombine knowledge and find
            // distance
            // wiki possible combinations
        } else {
            return '';
        }
    }
}
 /**
  * Up
  **/
 public function up()
 {
     $current = "<p>We have an online form to <a href=\"/change_password\" title=\"Change password form\">change your password</a>.  ";
     $current .= "You can use the link included here, or you can find the same link on the page that you go to when you first ";
     $current .= "<a href=\"/login\">log in</a> to this site.  You\\'ll also find the link on your ";
     $current .= "<a href=\"/mynanohub/account/\">My Account</a> page.</p>";
     $new = "<p>We have multiple methods available to help you change your password. ";
     $new .= "If you can't remember your password, go to the <a href=\"/login/reset\">forgot password</a> page to reset it. ";
     $new .= "If you're already logged in, and simply wish to change your password, go to your ";
     $new .= "<a href=\"/members/myaccount/account\">account page</a> for a quick password change form.</p>";
     $query = "SELECT * FROM `#__faq` WHERE `alias` = 'pwchange'";
     $this->db->setQuery($query);
     $results = $this->db->loadObjectList();
     if ($results && count($results) > 0) {
         foreach ($results as $r) {
             $sub1 = substr(stripslashes($r->fulltxt), 0, 254);
             $sub2 = substr($current, 0, 254);
             $distance = levenshtein($sub1, $sub2);
             if ($distance < 50) {
                 $query = "UPDATE `#__faq` SET `fulltxt` = " . $this->db->quote($new) . " WHERE `id` = " . $this->db->quote($r->id);
                 $this->db->setQuery($query);
                 $this->db->query();
             }
         }
     }
 }
예제 #21
0
 /**
  * This method manages the session fingerprint
  *
  * Check current client Fingerprint against the values saved in the session.
  * Save the current Fingerprint to the session
  * Rate the fingerprint match pass/fail based on any changes
  * On fail, clear the session, leaving only the new client fingerprint
  *
  * @param AttributeInterface $session session manager object or another
  *                                    AttributeInterface implementing object
  *
  * @return bool true if matched, false if not
  */
 public function checkSessionPrint(AttributeInterface $session)
 {
     $score = 0;
     // combined levenshtein distance of changes
     $changes = 0;
     // number of changed fields
     $currentFingerprint = $this->takePrint();
     $savedFingerprint = unserialize($session->get('SESSION_FINGERPRINT'));
     if ($savedFingerprint === false) {
         $savedFingerprint = $currentFingerprint;
         $changes = empty($_SESSION) ? 0 : 3;
         // in a populated session - force fail;
     }
     foreach ($currentFingerprint as $key => $current) {
         $distance = levenshtein($current, $savedFingerprint[$key]);
         $score += $distance;
         $changes += $distance > 0 ? 1 : 0;
     }
     $return = true;
     // if more than one field changed, or if that change is a distance greater than 30, fail it.
     if ($changes > 1 || $score > 30) {
         $session->clear();
         // session data should not be preserved
         $return = false;
     }
     $session->set('SESSION_FINGERPRINT', serialize($currentFingerprint));
     return $return;
 }
예제 #22
0
 /**
  * {@inheritdoc}
  */
 public function get($name)
 {
     $name = strtolower($name);
     if (!array_key_exists($name, $this->parameters)) {
         if (!$name) {
             throw new ParameterNotFoundException($name);
         }
         $alternatives = array();
         foreach ($this->parameters as $key => $parameterValue) {
             $lev = levenshtein($name, $key);
             if ($lev <= strlen($name) / 3 || false !== strpos($key, $name)) {
                 $alternatives[] = $key;
             }
         }
         $nonNestedAlternative = null;
         if (!count($alternatives) && false !== strpos($name, '.')) {
             $namePartsLength = array_map('strlen', explode('.', $name));
             $key = substr($name, 0, -1 * (1 + array_pop($namePartsLength)));
             while (count($namePartsLength)) {
                 if ($this->has($key)) {
                     if (is_array($this->get($key))) {
                         $nonNestedAlternative = $key;
                     }
                     break;
                 }
                 $key = substr($key, 0, -1 * (1 + array_pop($namePartsLength)));
             }
         }
         throw new ParameterNotFoundException($name, null, null, null, $alternatives, $nonNestedAlternative);
     }
     return $this->parameters[$name];
 }
예제 #23
0
function show_similar_codes($reference)
{
    $reference = strtolower($reference);
    $result = do_query("\n            SELECT deposref, uid FROM users WHERE uid > 1\n        UNION\n            SELECT deposref, uid FROM old_deposrefs\n        ORDER BY deposref\n    ");
    while ($row = mysql_fetch_assoc($result)) {
        $deposref = strtolower($row['deposref']);
        $scores[$deposref] = round((9 + similar_text($reference, $deposref) - levenshtein($reference, $deposref)) * 100 / 18);
        $uid[$deposref] = $row['uid'];
    }
    arsort($scores);
    $first = true;
    foreach ($scores as $deposref => $score) {
        if ($score >= 50) {
            if ($first) {
                $first = false;
                echo "<p>" . _("Did you mean one of these?  Higher percentage = closer match.") . "</p>\n";
                echo "<p>" . _("Click an entry to copy it to the form below, then click 'Deposit' again.") . "</p>\n";
                echo "<table class='display_data'>\n";
                echo "<tr><th>Reference</th><th>Match</th><th>UID</th></tr>\n";
            }
            $formatted = format_deposref($deposref);
            echo "<tr", " class=\"me\"", " onmouseover=\"style.backgroundColor='#8ae3bf';\"", " onmouseout=\"style.backgroundColor='#7ad3af';\"", " onclick=\"ObjById('reference').value = '{$deposref}';\">";
            echo "<td>{$formatted}</td><td>{$score}%</td><td>{$uid[$deposref]}</td></tr>\n";
        }
    }
    if (!$first) {
        echo "</table>\n";
    }
}
예제 #24
0
 /**
  * Use levenshtein's distance to decide what "good" url is most closest to the incomming request
  *
  * @param string request
  * @return array of result
  * - redirect the actually redirect to point to
  * - shortest how close this came
  */
 function findRedirectByRequest($request)
 {
     if ($this->settings['active']) {
         $retval = array('redirect' => '/', 'shortest' => -1);
         //Run import if we have no urls to look at.
         if ($this->find('count') == 0) {
             if ($this->import() == 0) {
                 return $retval;
             }
         }
         $urls = $this->find('all', array('fields' => array('SeoUrl.url'), 'recursive' => -1, 'order' => 'SeoUrl.priority ASC'));
         foreach ($urls as $url) {
             //Less efficent to use constants, if they're all the same don't use them
             if ($this->settings['cost_add'] == $this->settings['cost_change'] && $this->settings['cost_change'] == $this->settings['cost_delete']) {
                 $lev = levenshtein($request, $url['SeoUrl']['url']);
             } else {
                 $lev = levenshtein($request, $url['SeoUrl']['url'], $this->settings['cost_add'], $this->settings['cost_change'], $this->settings['cost_delete']);
             }
             if ($lev <= $retval['shortest'] || $retval['shortest'] < 0) {
                 $retval['redirect'] = $url['SeoUrl']['url'];
                 $retval['shortest'] = $lev;
             }
             if ($retval['shortest'] < $this->settings['threshold'] || $lev == 0) {
                 break;
             }
         }
         return $retval;
     }
     return false;
 }
 /**
  * {@inheritdoc}
  */
 public function handleError(array $error, FatalErrorException $exception)
 {
     preg_match('/^Call to undefined method (.*)::(.*)\\(\\)$/', $error['message'], $matches);
     if (!$matches) {
         return;
     }
     $className = $matches[1];
     $methodName = $matches[2];
     $message = sprintf('Attempted to call method "%s" on class "%s".', $methodName, $className);
     $candidates = array();
     foreach (get_class_methods($className) as $definedMethodName) {
         $lev = levenshtein($methodName, $definedMethodName);
         if ($lev <= strlen($methodName) / 3 || false !== strpos($definedMethodName, $methodName)) {
             $candidates[] = $definedMethodName;
         }
     }
     if ($candidates) {
         sort($candidates);
         $last = array_pop($candidates) . '"?';
         if ($candidates) {
             $candidates = 'e.g. "' . implode('", "', $candidates) . '" or "' . $last;
         } else {
             $candidates = '"' . $last;
         }
         $message .= ' Did you mean to call ' . $candidates;
     }
     return new UndefinedMethodException($message, $exception);
 }
예제 #26
0
function lev($str1, $str2)
{
    $levenshtein = levenshtein($str1, $str2);
    $lengthdifference = max($str1, $str2) - min($str1, $str2);
    $levenshtein -= $lengthdifference;
    $similarity = $levenshtein / strlen(min($str1, $str2));
    return $similarity;
}
예제 #27
0
 public function testSwap()
 {
     $orig = 'AAAAAAAAAA';
     for ($i = 0; $i < 10; $i = $i + 5) {
         $this->assertFalse($orig === self::swaprandbyte($orig));
         $this->assertEquals(levenshtein($orig, self::swaprandbyte($orig)), 1);
     }
 }
예제 #28
0
 private function distancesBy($value, array $candidateNames)
 {
     $distances = [];
     foreach ($candidateNames as $name) {
         $distances[$name] = levenshtein($value, $name);
     }
     return $distances;
 }
예제 #29
0
 public function testLevenshtein()
 {
     $this->assertSame(0, levenshtein('A', 'A'));
     $this->assertSame(1, levenshtein('A', 'a'));
     $this->assertSame(1, levenshtein('A', 'B'));
     $this->assertSame(1, levenshtein('A1', 'B1'));
     $this->assertSame(4, levenshtein('bat', 'nose'));
 }
예제 #30
0
 public function recognize($input = '', array $possibleCommands)
 {
     $mostPossibleResult = [];
     foreach ($possibleCommands as $pc) {
         $mostPossibleResult[levenshtein($input, $pc)] = $pc;
     }
     ksort($mostPossibleResult);
     return $mostPossibleResult;
 }