yetanotherape/diff-match-patch

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

v1.1.0 2020-12-20 17:28 UTC

This package is auto-updated.

Last update: 2024-09-21 00:42:31 UTC


README

Build Status Latest Stable Version Total Downloads

Diff Match和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-like格式应用到纯文本上。即使底层文本不匹配,也会尽力应用补丁。

用法

<?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和相同的功能。

算法

这个库实现了被认为是最通用的diff算法Myer's diff算法。围绕diff算法有一层预diff加速和后diff清理,提高了性能和输出质量。

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

要求

安装

composer require yetanotherape/diff-match-patch

许可

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