caxy / php-htmldiff

A library for comparing two HTML files/snippets and highlighting the differences using simple HTML. Includes support for comparing complex lists and tables
http://php-htmldiff.caxy.com
GNU General Public License v2.0
202 stars 51 forks source link

Feature: count of changed chars #76

Open arilia opened 6 years ago

arilia commented 6 years ago

Is there a way to have the count of the added/removed chars?

I need to show something like:

300 chars added, 600 chars removed

ajquick commented 4 years ago

This doesn't have to be done in the main code, though it certainly could be done through a stats() function or similar.

Here is generally how you would approach, but these are not the best coding practices:

$before = "before text here";
$after = "after text here";

$htmlDiff = new HtmlDiff($before, $after);
$content = $htmlDiff->build();

preg_match_all('/\<ins class\=\"([^"]+)\"\>([^<]+)\<\/ins\>/is', $content, $ins_matches);
preg_match_all('/\<del class\=\"([^"]+)\"\>([^<]+)\<\/del\>/is', $content, $del_matches);

$insert_count = 0;

for($i = 0; $i < count($ins_matches[1]); $i++){
    $insert_count += strlen($ins_matches[1][$i]);
}

$delete_count = 0;

for($i = 0; $i < count($del_matches[1]); $i++){
    $delete_count += strlen($del_matches[1][$i]);
}

echo $insert_count . ' chars added, ' . $delete_count .  ' chars removed';

Hope that helps!