keinos/mb_levenshtein

支持 UTF-8 的 Levenshtein 函数。

1.0.1 2022-01-09 01:34 UTC

This package is auto-updated.

Last update: 2024-09-09 07:46:38 UTC


README

Build Status

mb_levenshtein PHP 函数

支持 UTF-8 的 Levenshtein PHP 函数。此函数找出两个字符串之间的相似度距离。

函数

  • 返回 Levenshtein 距离。 (越小,越接近)

    mb_levenshtein ( string $str1 , string $str2 ) : int
    mb_levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del ) : int
  • 返回 0 到 1 之间的 Levenshtein 比率。 (越大,越接近)

    mb_levenshtein_ratio ( string $str1 , string $str2 ) : float
    mb_levenshtein_ratio ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del ) : float

用法

<?php
include_once('./mb_levenshtein.php');

$query = 'cafe';
$comps = [
    'coffee',
    'café',
    'tea',
    'sake',
];

echo "Query word: ${query}" . PHP_EOL;

foreach ($comps as $comp) {
    $sim = mb_levenshtein($query, $comp);
    echo "  ${comp}: ${sim}" . PHP_EOL;
}

结果

$ # The smaller, the closer
$ php ./sample.php
Query word: cafe
  coffee: 3
  café: 1
  tea: 4
  sake: 2

Composer

  • 使用发布版本

    composer require keinos/mb_levenshtein
  • 使用最新版本

    composer require keinos/mb_levenshtein:dev-master
<?php
require_once('vendor/autoload.php');

$query = 'cafe';
$comps = [
    'coffee',
    'café',
    'tea',
    'sake',
];

echo "Query word: ${query}" . PHP_EOL;

foreach ($comps as $comp) {
    $sim = mb_levenshtein($query, $comp);
    echo "  ${comp}: ${sim}" . PHP_EOL;
}

结果

$ ls
sample.php
$ composer require keinos/mb_levenshtein
Using version ^1.0 for keinos/mb_levenshtein
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing keinos/mb_levenshtein (1.0.0): Downloading (100%)
Writing lock file
Generating autoload files
$ # The smaller, the closer
$ php ./sample.php
Query word: cafe
  coffee: 3
  café: 1
  tea: 4
  sake: 2
$ ls
composer.json   composer.lock   sample.php  vendor
$ cat composer.json
{
    "require": {
        "keinos/mb_levenshtein": "^1.0"
    }
}