Last active
December 30, 2015 00:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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):