fadion / diff-match-patch
google-diff-match-patch (https://code.google.com/p/google-diff-match-patch/) 库的 PHP 版本
1.0.5
2020-05-21 11:11 UTC
Requires
- php: >=5.3
- ext-iconv: *
- ext-json: *
- ext-mbstring: *
Requires (Dev)
- phpunit/phpunit: 4.*
This package is auto-updated.
Last update: 2024-09-21 20:56:12 UTC
README
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
目前该库在以下语言中可用
- PHP
- C++
- C#
- Dart
- Java
- JavaScript
- Lua
- Objective-C
- Python
无论使用哪种语言,每个库都使用相同的 API 和相同的功能。
算法
该库实现了被普遍认为是最优的通用差异算法 Myer's diff 算法。一个预处理速度提升和后处理清理层围绕着差异算法,提高了性能和输出质量。
该库还实现了一个灵活的匹配和修补策略的核心 Bitap 匹配算法。
要求
- PHP 5.3+
- Composer
许可证
Diff-Match-Patch 在 Apache License 2.0 许可下发布 - 有关详细信息,请参阅 LICENSE
文件。