Jump to content

Archived

This topic is now archived and is closed to further replies.

shadowcaster

How do I highlight differences between strings?

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.