Skip to content

Instantly share code, notes, and snippets.

@abraunton
Last active December 30, 2015 00:49
Show Gist options
  • Save abraunton/7752072 to your computer and use it in GitHub Desktop.
Save abraunton/7752072 to your computer and use it in GitHub Desktop.
This is a simple PHP function that compares two strings and returns the differences in red. Call the function by using showdifferences("string one", "string two"). This will then show the original string but with the new changes in red and bold.
function showdifference($string1, $string2) {
// Both strings are split up by spaces, each word is now an item in an array.
$string1_array = explode(" ", $string1);
$string2_array = explode(" ", $string2);
// We will count both arrays to see which is the largest (used later).
$s1_count = count($string1_array);
$s2_count = count($string2_array);
// We need to use the largest number or else we may miss out something from the other array.
if($s1_count > $s2_count) {
$i = $s1_count;
} else {
$i = $s2_count;
}
// Set the counter to 0 (because the array keys start at 0)
$counter = 0;
// We will now check both arrays but using the same key we can compare words, if the words
// do not match then we will change the text to red and bolden it.
while ($i > $counter) {
echo " ";
if($string1_array[$counter] !== $string2_array[$counter]) {
echo "<span style='color:red;font-weight:bold;'>" . $string2_array[$counter]."</span>";
$counter++;
} else {
echo $string1_array[$counter];
$counter++;
}
}
// For testing, show both strings (in their origional form).
echo "<br /><br />Origional Text: <b>" . $string1 . "</b><br />";
echo "New Text: <b>" . $string2 . "</b>";
}
@xeoncross
Copy link

Since you need an array anyway, and this could be used for multiple types of arrays, (not just those separated with a space), do something like this (not tested):

function showdifference(array $a, array $b) {

    if(count($a) < count($b)) {
        $c = $a;
        $a = $b;
        $b = $c;
    }

    for($i = 0; $i < count($a); $i++) {
        echo " ";
        if( ! array_key_exists($i, $b) OR $a[$i] !== $b[$i]) {
            echo "<span style='color:red;font-weight:bold;'>" . $a[$i]."</span>";
            continue;
        }

        echo $a[$i];
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment