Thursday, 18 December 2014

Php compare strings and compute differences

Here is the php source code on how to compare two strings and compute the differences.
<?php
$text1 = $text1 = $s = ”;
if(isset($_POST[‘submit’]))
{
$text1 = $_POST[‘text1′];
$text2 = $_POST[‘text2′];
$chk = $_POST[‘chk’];
if($chk == ‘y’)
{
$s = ‘checked';
}
}
echo “<form method=post action=’strCompute.php’>
Text 1: <input type=text name=’text1′ value=’$text1′>
Text 2: <input type=text name=’text2′ value=’$text2′>
<input type=’checkbox’ name=’chk’ value=’y’ $s> Case Insensitive?
<input type=submit value=’Submit’ name=’submit’>
</form>”;
if($text1 == ”){ exit; }
$arrResult = computeDiff($text1, $text2, $chk);
$cntResult = count($arrResult);
echo “<p>Total Distance is $cntResult</p>”;
echo “<p>The differences character are:”;
foreach($arrResult as $value)
{
echo ” <font color=red><b>$value</b></font> “;
}
echo “</p>”;
function computeDiff($text1, $text2, $chk)
{
if($chk == ‘y’)
{
$text1 = strtolower($text1);
$text2 = strtolower($text2);
}
$array1 = str_split($text1);
$array2 = str_split($text2);
$result = array_diff_assoc($array1, $array2);
if(count($result) == 0)
{
$result = array_diff_assoc($array2, $array1);
}
return $result;
}
?>

No comments:

Post a Comment