2012-03-05 78 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;