PHP:删除两个字符串中的差异

时间:2012-03-05 19:59:57

标签: php mysql string string-comparison

示例,比较这两个字符串:

Hello Jake, blah blah blah. Sent at 1:23 AM

Hello Ben, blah blah blah. Sent at 3:12 PM

应该产生:

Hello [variable], blah blah blah. Sent at [variable]

我不需要显示旧的与旧的相比,只需删除差异(或者在这种情况下用文本“[variable]”替换它们。)

2 个答案:

答案 0 :(得分:4)

将空格(\ s)拆分为数组。

循环遍历数组进行比较,当值不匹配时,用[variable]替换,使用implode()返回字符串

答案 1 :(得分:0)

$string1 = explode(" ","Hello Jake, blah blah blah. Sent at 1:23 AM");
$string2 = explode(" ","Hello Ben, blah blah blah. Sent at  3:12 PM");
$finalString = explode(" ","Hello Ben, blah blah blah. Sent at  3:12 PM");


if($string1 > $string2)
{
$length = count($string2);
}
else
{
$length = count($string1);
}

for($i = 0; $i < $length; $i++)
{
if($string1[i] != $string2[i])
{ 
$finalString[i] = "[variable]";
}
}

$finalString = implode(" ", $finalString);
echo $finalString;