mistralys / text-diff
用于使用DIFF实现比较字符串的类。
2.0.2
2023-05-31 16:52 UTC
Requires
- php: >=7.4
- mistralys/application-utils: >=1.2.5
Requires (Dev)
- phpstan/phpstan: >=1.9
- phpunit/phpunit: >=9.6
This package is auto-updated.
Last update: 2024-08-30 01:20:27 UTC
README
PHP的DIFF字符串比较
用于使用DIFF实现比较两个字符串之间的差异的类,具有将diff渲染为带高亮的HTML的功能。
需求
- PHP 7.4+
- Composer
安装
通过composer要求
require mistralys/text-diff
或者通过GIT本地克隆,或者下载任何可用的发布版本。
用法
比较字符串
use Mistralys\Diff\Diff; $diff = Diff::compareStrings('String 1', 'String 2');
比较文件
use Mistralys\Diff\Diff; $diff = Diff::compareFiles('/path/to/file1', '/path/to/file2');
一旦创建了diff实例,可以选择任何toXXX
方法以获取你偏好的格式的diff。
use Mistralys\Diff\Diff; $diff = Diff::compareFiles('/path/to/file1', '/path/to/file2'); $string = $diff->toString(); $html = $diff->toHTML(); $table = $diff->toHTMLTable(); $array = $diff->toArray();
更改比较模式
默认情况下,比较将按行进行。它也可以更改为按字符进行
use Mistralys\Diff\Diff; $diff = Diff::compareFiles('/path/to/file1', '/path/to/file2'); $diff->setCompareCharacters(true);
HTML高亮显示
toHTML
和toHTMLTable
方法支持使用集成CSS样式来高亮显示更改。要插入这些,请使用Styler
类:它提供多种方法来访问CSS。
use Mistralys\Diff\Diff; $diff = Diff::compareFiles('/path/to/file1', '/path/to/file2'); $styler = Diff::createStyler();
从这里,根据项目的需求使用styler的任何方法。
use Mistralys\Diff\Diff; $styler = Diff::createStyler(); $css = $styler->getCSS(); // get the raw CSS styles $tag = $styler->getStyleTag(); // CSS styles with a <style> tag $path = $styler->getStylesheetPath(); // absolute path to the file $url = $styler->getStylesheetURL('/vendor'); // URL to the file, given the vendor folder URL
例如,要显示带内联样式的突出显示diff
use Mistralys\Diff\Diff; $diff = Diff::compareStrings('String 1', 'String 2'); echo Diff::createStyler()->getStyleTag(); echo $diff->toHTML();
致谢
原始Diff类由Kate Morley开发。与她的版本相比,这已经彻底重写。核心机制保持不变,但已更新为PHP7,并拆分为子类以使其更容易扩展和维护。静态比较方法仍然存在,但现在它们返回diff实例。
原始项目主页可在此处找到
http://code.iamkate.com/php/diff-implementation/
Kate已经从她的网站上移除了库,但我仍然保留它作为参考。