lbbniu/diff-match-patch

将 google-diff-match-patch (https://code.google.com/p/google-diff-match-patch/) 库移植到 PHP

v1.0.3 2018-10-23 03:04 UTC

This package is not auto-updated.

Last update: 2024-09-19 11:28:32 UTC


README

Build Status Latest Stable Version Total Downloads

Diff Match and Patch 库提供强大的算法,用于执行同步纯文本所需的操作

  • 计算两个文本的基于字符的差分
  • 执行给定字符串的模糊匹配
  • 应用一系列补丁。

这是将 Google 的 diff-match-patch 库移植到 PHP 的版本。

差分

比较两个纯文本,并高效地返回一个差异数组。它基于字符工作,但如果你想要基于单词或行的差分,你可以轻松地调整以满足你的需求。

用法

<?php

use DiffMatchPatch\DiffMatchPatch;

$text1 = "The quick brown fox jumps over the lazy dog.";
$text2 = "That quick brown fox jumped over a lazy dog.";
$dmp = new DiffMatchPatch();
$diffs = $dmp->diff_main($text1, $text2, false);
var_dump($diffs);

返回

array(
    array(DiffMatchPatch::DIFF_EQUAL, "Th"),
    array(DiffMatchPatch::DIFF_DELETE, "e"),
    array(DiffMatchPatch::DIFF_INSERT, "at"),
    array(DiffMatchPatch::DIFF_EQUAL, " quick brown fox jump"),
    array(DiffMatchPatch::DIFF_DELETE, "s"),
    array(DiffMatchPatch::DIFF_INSERT, "ed"),
    array(DiffMatchPatch::DIFF_EQUAL, " over "),
    array(DiffMatchPatch::DIFF_DELETE, "the"),
    array(DiffMatchPatch::DIFF_INSERT, "a"),
    array(DiffMatchPatch::DIFF_EQUAL, " lazy dog."),
)

演示

匹配

给定一个搜索字符串,在给定位置附近的纯文本中找到其最佳模糊匹配。同时考虑准确性和位置。

用法

<?php

use DiffMatchPatch\DiffMatchPatch;

$dmp = new DiffMatchPatch();
$text = "The quick brown fox jumps over the lazy fox.";
$pos = $dmp->match_main($text, "fox", 0); // Returns 16
$pos = $dmp->match_main($text, "fox", 40); // Returns 40
$pos = $dmp->match_main($text, "jmps"); // Returns 20
$pos = $dmp->match_main($text, "jmped"); // Returns -1
$pos = $dmp->Match_Threshold = 0.7;
$pos = $dmp->match_main($text, "jmped"); // Returns 20

演示

补丁

将一系列补丁应用到纯文本上,格式类似于 Unidiff。即使底层文本不匹配,也会尽力应用补丁。

用法

<?php

use DiffMatchPatch\DiffMatchPatch;

$dmp = new DiffMatchPatch();
$patches = $dmp->patch_make("The quick brown fox jumps over the lazy dog.", "That quick brown fox jumped over a lazy dog.");
// @@ -1,11 +1,12 @@
//  Th
// -e
// +at
//   quick b
// @@ -22,18 +22,17 @@
//  jump
// -s
// +ed
//   over
// -the
// +a
//   laz
$result = $dmp->patch_apply($patches, "The quick red rabbit jumps over the tired tiger.");
var_dump($result);

返回

array(
    "That quick red rabbit jumped over a tired tiger.",
    array (
        true,
        true,
    ),
);

演示

API

目前该库在以下语言中可用

无论语言如何,每个库都使用相同的 API 和相同的功能。

算法

此库实现了 Myer 的差分算法,这通常被认为是最好的通用差分算法。差分算法周围有一层 预差分加速和后差分清理,提高了性能和输出质量。

此库还实现了一个 Bitap 匹配算法,这是灵活的 匹配和补丁策略的核心。

需求

许可

Diff-Match-Patch 在 Apache License 2.0 下授权 - 有关详细信息,请参阅 LICENSE 文件