First of all, it sounds like by "string comparison" you really mean "word-by-word comparison." In otherwords, a literal character-by-character match wouldn't do you any good:
Old string: There onse was a man in nantucket
New string: There once was a man from Nantucket
Lining the two strings up like that shows you what I mean... "from Nantucket" would be considered "different" if you did a character-by-character analysis.
Instead, mogster's suggestion of exploding on spaces might work. You could then take each word of both strings and do a character-by-character analysis of those words. Something like this:
function compareStrings($oldString, $newString) {
$old_array = explode(' ', $oldString);
$new_array = explode(' ', $newString);
for($i=0; isset($old_array[$i]) || isset($new_array[$i]); $i++) {
if(!isset($old_array[$i])) {
echo '<font color="red">' . $new_array[$i] . '</font>';
continue;
}
for($char=0; isset($old_array[$i]{$char}) || isset($new_array[$i]{$char}); $char++) {
if(!isset($old_array[$i]{$char})) {
echo '<font color="red">' . substr($new_array[$i], $char) . '</font>';
break;
} elseif(!isset($new_array[$i]{$char})) {
break;
}
if(ord($old_array[$i]{$char}) != ord($new_array[$i]{$char}))
echo '<font color="red">' . $new_array[$i]{$char} . '</font>';
else
echo $new_array[$i]{$char};
}
if(isset($new_array[$i+1]))
echo ' ';
}
}
Somethings to know about this function I created:
- If the word in the "new" string is shorter than the corresponding word in the old string, no extra highlighting will be done. You can change the behavior of this, but I just didn't know how you wanted that situation handled.
- This function will print out the newly highlighted string. If you instead wanted to store it's contents in a variable, some modifications would be needed.
- I'm a bit tired this morning, so there are probably some optimizations you could do (especially if you're using really large strings). But for the most part, I think it's okay...