Search by

ergebnis / differ

localheinz

Provides a composer package with a differ for creating a unified diff of two strings.

1.0.0 2026-11-12 17:53 UTC

README

Integrate Merge Release Renew

Code Coverage

Latest Stable Version Total Downloads Monthly Downloads

This project provides a composer package with a differ for creating a unified diff of two strings.

Installation

Run

composer require ergebnis/differ

Usage

Create a MyersDiffer, then call diff() with a From and a To, each made of a Label and a Text, to receive a Diff of the lines of both Texts:

<?php

declare(strict_types=1);

use Ergebnis\Differ;

$differ = new Differ\MyersDiffer();

$diff = $differ->diff(
    Differ\From::create(
        Differ\Label::fromString('original'),
        Differ\Text::fromString("foo\nbar\nbaz\n"),
    ),
    Differ\To::create(
        Differ\Label::fromString('changed'),
        Differ\Text::fromString("foo\nqux\nbaz\n"),
    ),
);

echo $diff->toString();

This prints

--- original
+++ changed
@@ -1,3 +1,3 @@
 foo
-bar
+qux
 baz

When both Texts are identical, Diff::isEmpty() returns true and Diff::toString() returns an empty string.

MyersDiffer implements the Differ interface, which you can use as a type declaration.

Label::fromString() throws an InvalidLabel exception when the value contains a line break, because a line break would break the header of the diff.

When both Texts end with a new line, Diff::toString() returns the same unified diff as sebastian/diff with its StrictUnifiedDiffOutputBuilder.

Changelog

The maintainers of this project record notable changes to this project in a changelog.

Contributing

The maintainers of this project suggest following the contribution guide.

Code of Conduct

The maintainers of this project ask contributors to follow the code of conduct.

General Support Policy

The maintainers of this project provide limited support.

PHP Version Support Policy

This project currently supports the following PHP versions:

The maintainers of this project add support for a PHP version following its initial release and may drop support for a PHP version when it has reached its end of life.

Security Policy

This project has a security policy.

License

This project uses the MIT license.

Credits

The algorithm for computing the diff in MyersDiffer has been adopted from SebastianBergmann\Diff\MyersDiff and SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder (originally licensed under BSD-3-Clause by Sebastian Bergmann), which implement the linear-space variant of the algorithm described by Eugene W. Myers in "An O(ND) Difference Algorithm and Its Variations".

Social

Follow @localheinz and @ergebnis on X.