caxy/php-htmldiff

Feature: count of changed chars

arilia opened this issue · 1 comments

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

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!