2012-03-05 67 views
-1

实例删除的差异,比较这两个字符串:PHP:在两个字符串

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] 

我并不需要显示相比,新的一个旧,只是删除差异(或在这种情况下,用文本“[变量]”替换它们)。

+2

将帮助你解决你自己尝试免费,但将只写你的代码为你的钱 – 2012-03-05 20:12:07

+0

可能重复[突出显示两个字符串在PHP中的区别](http://stackoverflow.com/questions/321294/highlight-the-difference-between-two-strings-in- php) – 2012-03-05 20:32:54

回答

4

将空间(\ s)分割为数组。

遍历数组进行比较,当值不匹配,更换[变量],使用破灭()进行回字符串

+2

如果有人说“Hello fthaluhft9awt7 7f8aw78t jaw78f87tj aw,blah blah blah。Sent at 3:12 PM”怎么办? – 2012-03-05 20:09:56

+0

你会通过这两个数组循环而不是仅仅使用['array_diff_assoc()'](http://www.php.net/manual/en/function.array-diff-assoc.php),Andrew? – 2012-03-05 20:11:30

+1

@Sarcsam - 你仍然可以使用像array_intersect() – 2012-03-05 20:14:25

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;