Compare two Strings and print the texts marking the differences between them in PHP

Here is a function that compares two strings and outputs the strings, with different letters or words marked. This function first splits the two strings into arrays of words. It then loops through each of the arrays and compares the words, marking any that are different in red. The output is displayed as two columns, with each of the strings displayed in separate columns.

<?php

function compare_strings($string1, $string2)
{

    $string1_arr = explode(" ", $string1);
    $string2_arr = explode(" ", $string2);

    echo "<div style='float:left;width:50%;'>\n";
    for ($i = 0; $i < count($string1_arr); $i++) {
        if ($string1_arr[$i] != $string2_arr[$i]) {
            echo "<span style='color:red;'>" . $string1_arr[$i] . "</span> ";
        } else {
            echo $string1_arr[$i] . " ";
        }
    }
    echo "\n</div>\n";

    echo "<div style='float:left;width:50%;'>\n";
    for ($i = 0; $i < count($string2_arr); $i++) {
        if ($string1_arr[$i] != $string2_arr[$i]) {
            echo "<span style='color:red;'>" . $string2_arr[$i] . "</span> ";
        } else {
            echo $string2_arr[$i] . " ";
        }
    }
    echo "\n</div>\n";
}

compare_strings("Hello world! This is an example ...", "Helo world! This is am example ...");

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *