shadowcaster Posted April 3, 2006 Share Posted April 3, 2006 Hello. I'm not sure if this is a newbie question but imagine I have two strings:[code]$string1 = "The quick brown brown fox jumps over the lazy dog.";$string2 = "The quick brown albino fox jumps over the groovy dog.";[/code]How would I compare the strings and then highlight the differences compared to $string1 so that the words albino and groovy stand out? Quote Link to comment Share on other sites More sharing options...
sanfly Posted April 4, 2006 Share Posted April 4, 2006 Is this what you were after?[code]<? $string1 = "The quick brown brown fox jumps over the lazy dog."; $string2 = "The quick brown albino fox jumps over the groovy dog."; $string1 = explode(" ", $string1); $string2 = explode(" ", $string2); $i = 0; foreach($string2 as $value){ if($value != $string1[$i]){ echo "<b>$value </b>"; } else { echo "$value "; } $i++; } ?>[/code] Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted April 4, 2006 Share Posted April 4, 2006 One minor change to the above solution will alliviate the space the end of the new string... This procedure assumes the strings are of equal length.[code]<?php $string1 = "The quick brown brown fox jumps over the lazy dog."; $string2 = "The quick brown albino fox jumps over the groovy dog."; $string1 = explode(" ", $string1); $string2 = explode(" ", $string2); $tmp = array(); foreach($string2 as $k=>$value){ if($value != $string1[$k]){ $tmp[] = "<b>$value </b>"; } else { $tmp[] = $value; } $i++; } echo implode(' ',$tmp);?>[/code]Ken Quote Link to comment Share on other sites More sharing options...
shadowcaster Posted April 5, 2006 Author Share Posted April 5, 2006 Cheers guys :) Quote Link to comment Share on other sites More sharing options...
Barand Posted April 5, 2006 Share Posted April 5, 2006 This version will show [b]added [/b]and [missing] words.[code] $string1 = "The quick brown fox jumps over the lazy dog."; $string2 = "The quick brown albino fox jumps the groovy dog."; $string1 = explode(" ", $string1); $string2 = explode(" ", $string2); $diff = array_intersect($string2, $string1); $tmp = array(); foreach ($string2 as $k => $w) { if ($diff[$k]==$w) { $tmp[$k] = $w; } else { $tmp[$k] = "<b>$w</b>"; } } $diff = array_diff($string1, $tmp); foreach ($diff as $k => $w) { $tmp[$k] .= " [<strike>$w</strike>]"; } echo join (' ', $tmp);[/code] Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.