用两个单词计算重复字母的PHP代码

时间:2013-02-18 07:52:27

标签: php on-duplicate-key

嗨,我是php的新手,我想问一下如何编写一个代码,将两个单词中重复的字母数量排除在外。     例如:“苹果”和“球”整体上有7个相同的字母(a,a,p,p,l,l,l)提前谢谢你:)

6 个答案:

答案 0 :(得分:1)

不是最有效但可以说是简单的:

$word1 = "apple";
$word2 = "ball";
print_r(array_count_values(str_split($word1.$word2)));

输出:

Array
(
    [a] => 2
    [p] => 2
    [l] => 3
    [e] => 1
    [b] => 1
)

答案 1 :(得分:1)

你可以这样做。

$a = 'apple';
$b = 'ball';

$duplicates = array_count_values(array_merge(str_split($a), str_split($b)));

// Array ( [a] => 2 [p] => 2 [l] => 3 [e] => 1 [b] => 1 )
print_r($duplicates);

如果您想获得单词之间的匹配总数,则可以执行此操作。

$totalMatches = 0;

foreach($duplicates as $count) {
    if($count > 1)
        $totalMatches += $count;
}

// 7 matches!
echo $totalMatches . ' matches!';

答案 2 :(得分:0)

尝试str_split从字符串生成数组,然后比较数组本身和其他重复输入。

答案 3 :(得分:0)

可能是这样的:

$a= "apple";
$a.=  "ball";
print_r(array_count_values(str_split($a)));

输出:

Array
(
    [a] => 2
    [p] => 2
    [l] => 3
    [e] => 1
    [b] => 1
)

答案 4 :(得分:0)

$str1   = "apple";
$ar1    = str_split($str1);

$str2   = "ball";
$ar2    = str_split($str2);

$res    = array_merge($ar1,$ar2);
$count  = array_count_values($res);

print_r($count);

答案 5 :(得分:0)

<?php

$str1 = 'applle';
$str2 = 'ball';
$str1arr = str_split($str1);
$str2arr = str_split($str2);
$all = array_merge($str1arr, $str2arr);
$countall = count($all) - count(array_intersect($str1arr, $str2arr));
echo "count of similar charactors (overall) =".($countall);//7!

?>