jfcherng/php-levenshtein-distance

计算两个字符串之间的Levenshtein距离和编辑过程。

4.0.2 2022-05-31 13:28 UTC

This package is auto-updated.

Last update: 2024-09-16 22:28:24 UTC


README

GitHub Workflow Status (branch) Packagist Packagist Version Project license GitHub stars Donate to this project using Paypal

计算两个字符串之间的Levenshtein距离和编辑过程。注意,如果您不需要编辑路径,PHP有一个内置的levenshtein()函数。

特性

  • UTF-8兼容。
  • 完整的编辑过程信息。

安装

$ composer require jfcherng/php-levenshtein-distance

示例

参见demo.php

<?php

include __DIR__ . '/vendor/autoload.php';

use Jfcherng\Diff\LevenshteinDistance as LD;

$old = '自訂取代詞語模組';
$new = '自订取代词语模组!';

$calculator = new LD(
    true, // calculate edit progresses?
    // progress options
    LD::PROGRESS_OP_AS_STRING | LD::PROGRESS_PATCH_MODE
);

$results = $calculator->calculate($old, $new);

// this is the same but using an internal singleton
$results = LD::staticCalculate(
    $old, // old string
    $new, // new string
    true, // calculate edit progresses?
    // progress options
    LD::PROGRESS_OP_AS_STRING | LD::PROGRESS_PATCH_MODE
);

// [
//     'distance' => 5,
//     'progresses' => [
//         ['ins', 8, '!', 1],
//         ['rep', 7, '组', 1],
//         ['cpy', 6, '模', 1],
//         ['rep', 5, '语', 1],
//         ['rep', 4, '词', 1],
//         ['cpy', 3, '代', 1],
//         ['cpy', 2, '取', 1],
//         ['rep', 1, '订', 1],
//         ['cpy', 0, '自', 1],
//     ],
// ]
var_dump($results);

$results = LD::staticCalculate(
    $old, // old string
    $new, // new string
    true, // calculate edit progresses?
    // progress options
    LD::PROGRESS_OP_AS_STRING | LD::PROGRESS_PATCH_MODE | LD::PROGRESS_MERGE_NEIGHBOR
);

// [
//     'distance' => 5,
//     'progresses' => [
//         ['ins', 8, '!', 1],
//         ['rep', 7, '组', 1],
//         ['cpy', 6, '模', 1],
//         ['rep', 4, '词语', 2],
//         ['cpy', 2, '取代', 2],
//         ['rep', 1, '订', 1],
//         ['cpy', 0, '自', 1],
//     ],
// ]
var_dump($results);

进度选项

  • LD::PROGRESS_NO_COPY:在进度中不包括COPY操作。
  • LD::PROGRESS_MERGE_NEIGHBOR:如果可能,合并相邻的进度。
  • LD::PROGRESS_OP_AS_STRING:将进度中的操作从int转换为字符串。
  • LD::PROGRESS_PATCH_MODE:用相应的字符串替换新的编辑位置。

返回的progresses

  1. 操作。
  2. 新字符串的编辑位置。
  3. 旧字符串的编辑位置。如果使用LD::PROGRESS_PATCH_MODE,则对应字符串。
  4. 编辑长度。