2016-09-16 1 views
-1

私は短い文字列の長さと違いのテーマの数を返すために2つの文字列を比較したいと思います。例えば:phpの2つの文字列の違いの数をどのように数えますか?

$first_str = "abcdez"; 
$second_str= "abhdx"; 

今による$second_strの長さに短くなっているので、彼らは、第3および第4のインデックスのみが異なるので、リターン2でなければなりません。実際には等しいインデックスと比較されます。 phpでこの作品のための関数はありますか?そうでない場合は、コードを書くために私を助けることができますか?

+1

を示す配列を持つことになります

$a_first_str = str_split($first_str); $a_second_str = str_split($second_str); $diff=array_diff_assoc($a_second_str, $a_first_str); 

を動作するはず? –

+2

なぜ '2'ですか? 'c'、' e'、 'z'は2番目の文字列にはありません。 – chris85

+1

@Patrick Mlr。はい。最初の文字列の最初の文字列と2番目の文字列の最初の文字列... –

答えて

0

おそらくこれが役に立ちます。私はAnantからコメントをフォークしました。

$first_str = "abcdez"; 
$second_str= "abhdx"; 

$first_str_array = str_split($first_str); 

$second_str_array = str_split($second_str); 

$first_count = count($first_str_array); 
$second_count = count($second_str_array); 

if (($first_count - $second_count) > 0) { 
    $count = $first_count - $second_count; 
    unset($first_str_array[$first_count-$count]); 
} else if (($second_count - $first_count) > 0){ 
    $count = $second_count - $first_count; 
    unset($second_str_array[$second_count-$count]); 
} 

$final_difference = array_diff($first_str_array,$second_str_array); 
+0

最後にcount($ final_difference)うまくいった。ありがとうございます。最も完全な答え:) –

2

配列はこのようなものには適しています。私はそれをテストしていないが、それはあなたが文字を比較したい差分

+0

うん、それはそれを行います。ちょうど 'count()'で '$ diff'を実行すると、違いの数が得られます。 –

関連する問題