Php compare strings and compute differences

Posted: March 23, 2010 in Php
Tags: , ,

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;
}

?>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s