{"id":18551972,"url":"https://github.com/baraja-core/simple-php-diff","last_synced_at":"2026-02-03T13:12:07.704Z","repository":{"id":44444409,"uuid":"352579192","full_name":"baraja-core/simple-php-diff","owner":"baraja-core","description":"Find the quick difference between two text files in PHP.","archived":false,"fork":false,"pushed_at":"2022-09-07T11:29:44.000Z","size":133,"stargazers_count":11,"open_issues_count":1,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-08-23T21:21:48.045Z","etag":null,"topics":["compare","comparison","comparison-modes","default-theme","diff","html","php","php-diff"],"latest_commit_sha":null,"homepage":"https://php.baraja.cz","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/baraja-core.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/funding.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":"janbarasek","custom":["https://baraja.cz","https://php.baraja.cz","https://vue.baraja.cz"]}},"created_at":"2021-03-29T09:02:13.000Z","updated_at":"2025-07-13T21:17:12.000Z","dependencies_parsed_at":"2022-07-14T00:20:27.296Z","dependency_job_id":null,"html_url":"https://github.com/baraja-core/simple-php-diff","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/baraja-core/simple-php-diff","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baraja-core%2Fsimple-php-diff","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baraja-core%2Fsimple-php-diff/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baraja-core%2Fsimple-php-diff/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baraja-core%2Fsimple-php-diff/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/baraja-core","download_url":"https://codeload.github.com/baraja-core/simple-php-diff/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baraja-core%2Fsimple-php-diff/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29046503,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-03T10:09:22.136Z","status":"ssl_error","status_checked_at":"2026-02-03T10:09:16.814Z","response_time":96,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["compare","comparison","comparison-modes","default-theme","diff","html","php","php-diff"],"created_at":"2024-11-06T21:11:22.067Z","updated_at":"2026-02-03T13:12:07.694Z","avatar_url":"https://github.com/baraja-core.png","language":"PHP","funding_links":["https://github.com/sponsors/janbarasek","https://baraja.cz","https://php.baraja.cz","https://vue.baraja.cz"],"categories":[],"sub_categories":[],"readme":"# Simple PHP Diff\n\nA lightweight PHP library for fast text comparison and difference visualization. Find the quick difference between two text files and render the results in plain text or HTML format.\n\n## Key Principles\n\n- **Line-by-line comparison** - Compares texts line by line with numbered output for easy change tracking\n- **Immutable result object** - Returns a `Diff` object containing original, target, formatted diff, and changed line numbers\n- **Dual output modes** - Plain text diff output and styled HTML rendering with color-coded changes\n- **Strict mode support** - Optional strict comparison that preserves different line ending formats\n- **Whitespace visualization** - Pretty rendering shows tabs as arrows and spaces as dots for clarity\n- **Zero dependencies** - Pure PHP implementation requiring only PHP 8.0+\n\n## Architecture\n\nThe library consists of two main components with a clean separation of concerns:\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│                        SimpleDiff                           │\n│  ┌─────────────────────────────────────────────────────┐   │\n│  │  compare($left, $right, $strict)                    │   │\n│  │  - Normalizes line endings (non-strict mode)        │   │\n│  │  - Performs line-by-line comparison                 │   │\n│  │  - Tracks changed line numbers                      │   │\n│  │  - Formats output with line numbers                 │   │\n│  └─────────────────────────────────────────────────────┘   │\n│                           │                                 │\n│                           ▼                                 │\n│  ┌─────────────────────────────────────────────────────┐   │\n│  │  renderDiff($diff)                                  │   │\n│  │  - Converts diff to styled HTML                     │   │\n│  │  - Color-codes additions (green) / removals (red)   │   │\n│  └─────────────────────────────────────────────────────┘   │\n└─────────────────────────────────────────────────────────────┘\n                            │\n                            ▼\n┌─────────────────────────────────────────────────────────────┐\n│                          Diff                               │\n│  Immutable Value Object                                     │\n│  ┌─────────────────────────────────────────────────────┐   │\n│  │  - original: string     (normalized left input)     │   │\n│  │  - target: string       (normalized right input)    │   │\n│  │  - diff: string         (formatted diff output)     │   │\n│  │  - changedLines: int[]  (line numbers that changed) │   │\n│  └─────────────────────────────────────────────────────┘   │\n└─────────────────────────────────────────────────────────────┘\n```\n\n## Components\n\n### SimpleDiff\n\nThe main comparison engine that processes two text inputs and generates a diff result.\n\n**Methods:**\n\n| Method | Description |\n|--------|-------------|\n| `compare(string $left, string $right, bool $strict = false): Diff` | Compares two strings and returns a `Diff` object |\n| `renderDiff(Diff\\|string $diff): string` | Renders the diff as styled HTML |\n\n**Comparison Process:**\n\n1. **Input normalization** (non-strict mode): Converts all line endings (`\\r\\n`, `\\r`) to `\\n` and trims whitespace\n2. **Line splitting**: Splits both inputs into arrays by newline character\n3. **Line-by-line comparison**: Iterates through lines, comparing original vs target\n4. **Output formatting**: Prepends each line with status marker (`+`, `-`, or space) and line number\n5. **Change tracking**: Records line numbers where differences occur\n\n### Diff\n\nAn immutable value object that encapsulates the comparison result.\n\n**Properties (via getters):**\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `original` | `string` | The normalized left/original input text |\n| `target` | `string` | The normalized right/target input text |\n| `diff` | `string` | The formatted diff output with line markers |\n| `changedLines` | `int[]` | Array of line numbers (1-indexed) that differ |\n\n**String Conversion:**\n\nThe `Diff` object implements `__toString()` which returns the formatted diff string, allowing direct string casting.\n\n## 📦 Installation\n\nIt's best to use [Composer](https://getcomposer.org) for installation, and you can also find the package on\n[Packagist](https://packagist.org/packages/baraja-core/simple-php-diff) and\n[GitHub](https://github.com/baraja-core/simple-php-diff).\n\nTo install, simply use the command:\n\n```shell\n$ composer require baraja-core/simple-php-diff\n```\n\nYou can use the package manually by creating an instance of the internal classes, or register a DIC extension to link the services directly to the Nette Framework.\n\n### Requirements\n\n- PHP 8.0 or higher\n\n## Basic Usage\n\n### Simple Text Comparison\n\n```php\nuse Baraja\\DiffGenerator\\SimpleDiff;\n\n$left = 'First text';\n$right = 'Second text';\n\n$diff = (new SimpleDiff)-\u003ecompare($left, $right);\n\n// Output the diff as plain text\necho '\u003ccode\u003e\u003cpre\u003e' . htmlspecialchars((string) $diff) . '\u003c/pre\u003e\u003c/code\u003e';\n```\n\n### Get Changed Line Numbers\n\n```php\n$diff = (new SimpleDiff)-\u003ecompare($left, $right);\n\necho 'Changed lines: ' . implode(', ', $diff-\u003egetChangedLines());\n```\n\n### Render Diff as HTML\n\n```php\n$simpleDiff = new SimpleDiff;\n$diff = $simpleDiff-\u003ecompare($left, $right);\n\n// Returns styled HTML with color-coded changes\necho $simpleDiff-\u003erenderDiff($diff);\n```\n\n## Output Format\n\n### Plain Text Output\n\nThe diff output uses a standardized format:\n\n```\n  1| unchanged line\n- 2| removed·line·with·visible·spaces\n+ 2| added→→→→line·with·visible·tabs\n  3| another unchanged line\n```\n\n**Format explanation:**\n\n- Lines starting with `  ` (two spaces) are unchanged\n- Lines starting with `- ` indicate content from the original (left) text\n- Lines starting with `+ ` indicate content from the target (right) text\n- Line numbers are right-padded and followed by `| `\n- Spaces are rendered as `·` (middle dot)\n- Tabs are rendered as `→→→→` (four arrows)\n\n### HTML Output\n\nThe `renderDiff()` method generates HTML with inline styles:\n\n```html\n\u003cpre class=\"code\"\u003e\n\u003cdiv\u003e  1| unchanged line\u003c/div\u003e\n\u003cdiv style=\"background:#e7acac\"\u003e- 2| removed line\u003c/div\u003e\n\u003cdiv style=\"background:#a2f19c\"\u003e+ 2| added line\u003c/div\u003e\n\u003cdiv\u003e  3| another unchanged line\u003c/div\u003e\n\u003c/pre\u003e\n```\n\n**Color coding:**\n\n- **Green background** (`#a2f19c`): Added lines (prefixed with `+`)\n- **Red background** (`#e7acac`): Removed lines (prefixed with `-`)\n- **No background**: Unchanged lines\n\n## Visual Examples\n\n### Plain Text Diff Output\n\n![Plain text diff](doc/simple-diff.png)\n\n### HTML Rendered Diff\n\n![HTML rendered diff](doc/diff-to-html.png)\n\n## Comparison Modes\n\n### Non-Strict Mode (Default)\n\nIn non-strict mode (default), the library normalizes line endings before comparison:\n\n- Converts `\\r\\n` (Windows) to `\\n`\n- Converts `\\r` (old Mac) to `\\n`\n- Trims leading and trailing whitespace from both inputs\n\nThis mode is ideal for comparing content where line ending differences should be ignored.\n\n```php\n// Non-strict comparison (default)\n$diff = (new SimpleDiff)-\u003ecompare($left, $right);\n$diff = (new SimpleDiff)-\u003ecompare($left, $right, false);\n```\n\n### Strict Mode\n\nStrict mode preserves the original line endings and whitespace, useful when you need to detect differences in line termination characters.\n\n```php\n// Strict comparison - preserves line endings\n$diff = (new SimpleDiff)-\u003ecompare($left, $right, true);\n```\n\n## Working with the Diff Object\n\n### Accessing Original and Target Text\n\n```php\n$diff = (new SimpleDiff)-\u003ecompare($left, $right);\n\n// Get the normalized original text\n$original = $diff-\u003egetOriginal();\n\n// Get the normalized target text\n$target = $diff-\u003egetTarget();\n```\n\n### Getting the Raw Diff String\n\n```php\n$diff = (new SimpleDiff)-\u003ecompare($left, $right);\n\n// Using getter method\n$diffString = $diff-\u003egetDiff();\n\n// Using string casting (equivalent)\n$diffString = (string) $diff;\n```\n\n### Working with Changed Lines\n\n```php\n$diff = (new SimpleDiff)-\u003ecompare($left, $right);\n$changedLines = $diff-\u003egetChangedLines();\n\n// Example output: [2, 5, 8] - lines 2, 5, and 8 were modified\nforeach ($changedLines as $lineNumber) {\n    echo \"Line {$lineNumber} was changed\\n\";\n}\n\n// Check if any changes occurred\nif (count($changedLines) === 0) {\n    echo \"No differences found!\";\n}\n```\n\n## Advanced Examples\n\n### Comparing Files\n\n```php\n$originalFile = file_get_contents('/path/to/original.txt');\n$modifiedFile = file_get_contents('/path/to/modified.txt');\n\n$simpleDiff = new SimpleDiff;\n$diff = $simpleDiff-\u003ecompare($originalFile, $modifiedFile);\n\n// Check if files are identical\nif (empty($diff-\u003egetChangedLines())) {\n    echo \"Files are identical.\";\n} else {\n    echo \"Files differ on lines: \" . implode(', ', $diff-\u003egetChangedLines());\n    echo \"\\n\\n\";\n    echo $diff;\n}\n```\n\n### Custom HTML Rendering\n\nIf you need custom styling, you can process the diff string yourself:\n\n```php\n$diff = (new SimpleDiff)-\u003ecompare($left, $right);\n\n$lines = explode(\"\\n\", $diff-\u003egetDiff());\n$html = '\u003cdiv class=\"my-diff-container\"\u003e';\n\nforeach ($lines as $line) {\n    $firstChar = $line[0] ?? '';\n    $cssClass = match ($firstChar) {\n        '+' =\u003e 'diff-added',\n        '-' =\u003e 'diff-removed',\n        default =\u003e 'diff-unchanged',\n    };\n    $html .= sprintf('\u003cdiv class=\"%s\"\u003e%s\u003c/div\u003e', $cssClass, htmlspecialchars($line));\n}\n\n$html .= '\u003c/div\u003e';\necho $html;\n```\n\n### Integration with Version Control Display\n\n```php\nfunction showCommitDiff(string $oldContent, string $newContent): string\n{\n    $simpleDiff = new SimpleDiff;\n    $diff = $simpleDiff-\u003ecompare($oldContent, $newContent);\n\n    $changedCount = count($diff-\u003egetChangedLines());\n\n    $output = \"\u003ch3\u003eChanges: {$changedCount} line(s) modified\u003c/h3\u003e\";\n    $output .= $simpleDiff-\u003erenderDiff($diff);\n\n    return $output;\n}\n```\n\n## Author\n\n**Jan Barášek** - [https://baraja.cz](https://baraja.cz)\n\n## 📄 License\n\n`baraja-core/simple-php-diff` is licensed under the MIT license. See the [LICENSE](https://github.com/baraja-core/simple-php-diff/blob/master/LICENSE) file for more details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbaraja-core%2Fsimple-php-diff","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbaraja-core%2Fsimple-php-diff","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbaraja-core%2Fsimple-php-diff/lists"}