Skip to content

Instantly share code, notes, and snippets.

@lunule
Created January 1, 2024 17:08
Show Gist options
  • Save lunule/d2aedbeb3c339704e2e700fe433c7c8c to your computer and use it in GitHub Desktop.
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
<?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