Created
January 1, 2024 17:08
-
-
Save lunule/d2aedbeb3c339704e2e700fe433c7c8c to your computer and use it in GitHub Desktop.
[PHP - Find & Format Difference Between 2 Strings] #php #diff #testing #var_dump #beautify https://web.archive.org/web/20210411151537/https://coderwall.com/p/3j2hxq/find-and-format-difference-between-two-strings-in-php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_decorated_diff($old, $new){ | |
$from_start = strspn($old ^ $new, "\0"); | |
$from_end = strspn(strrev($old) ^ strrev($new), "\0"); | |
$old_end = strlen($old) - $from_end; | |
$new_end = strlen($new) - $from_end; | |
$start = substr($new, 0, $from_start); | |
$end = substr($new, $new_end); | |
$new_diff = substr($new, $from_start, $new_end - $from_start); | |
$old_diff = substr($old, $from_start, $old_end - $from_start); | |
$new = "$start<ins style='background-color:#ccffcc'>$new_diff</ins>$end"; | |
$old = "$start<del style='background-color:#ffcccc'>$old_diff</del>$end"; | |
return array("old"=>$old, "new"=>$new); | |
} | |
// Usage | |
$string_old = "The quick brown fox jumped over the lazy dog"; | |
$string_new = "The quick white rabbit jumped over the lazy dog"; | |
$diff = get_decorated_diff($string_old, $string_new); | |
echo "<table> | |
<tr> | |
<td>".$diff['old']."</td> | |
<td>".$diff['new']."</td> | |
</tr> | |
</table>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment