Home > Back-end >  my php diff checker code works fine on a single word but not in the setences
my php diff checker code works fine on a single word but not in the setences

Time:10-19

I am writing a php program to compare two strings of equal length and highlight the difference. My code works fine on single words. But when I enter a sentence to compare, then it prints out the html parts of my code in unusual manner.

<form action="#" method="post">
<input type="text" name="first"><br>
<input type="text" name="second"><br>
<input type="submit" name="">

</form>
<?php 
$var1=$_POST['first'];
$var2=$_POST['second'];
echo $var1;
echo "<br>";
$var3=$var2;
$temp =$var2;
$diff_char1='';

for ($i=0;$i<strlen($var1);$i  ) { 
        // code...
        if ($var1[$i]==$var2[$i]) {
            // code...
        //  echo "true<br>";
        }
        else{
                // code...
            $diff_char = substr($var2, $i,1);
                        //echo"<br>".$diff_char;
            $diff_char1='<span style="background:red">'.$diff_char.'</span>';

            //echo $diff_char1.'<br>';
            $temp= str_replace($diff_char,$diff_char1,$temp);
            //echo $temp."<br>";
        

            
        }
    }
    
    
        echo $temp;
    

     ?>

CodePudding user response:

Rather than modifying the content as you process the string you could simply build a new string that reflects the differences and present that at the end to show the differences - perhaps like this:

<?php
    error_reporting( E_ALL );
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <style>
            output span{color:red}
        </style>
    </head>
    <body>
        <form method="post">
            <input type="text" name="first" />
            <input type="text" name="second" />
            <input type="submit" />
        </form>
        <output>
        <?php
            if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
                $_POST['first'],
                $_POST['second']
            )){
                $first=$_POST['first'];
                $second=$_POST['second'];
                $message='';
                
                if( substr_compare( $first, $second, 0 )===0 ){
                    $message='Strings are identical';
                } elseif( strlen( $first )!=strlen( $second ) ){
                    $message='Strings are of different lengths';
                }else{
                    for( $i=0; $i < strlen( $first ); $i   ){
                        $chr1=substr($first,$i,1);
                        $chr2=substr($second,$i,1);
                        if( $chr1!==$chr2 )$message.=sprintf('<span>%s</span>',$chr2);
                        else $message.=$chr1;
                    }
                }
                
                echo $message;
             }
        ?>
        </output>
    </body>
</html>
  •  Tags:  
  • php
  • Related