php-htmldiff icon indicating copy to clipboard operation
php-htmldiff copied to clipboard

Feature: count of changed chars

Open arilia opened this issue 7 years ago • 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

arilia avatar Jul 12 '18 09:07 arilia

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!

ajquick avatar Dec 09 '19 02:12 ajquick