用户1编写了一个单词(单词1),我想计算对手单词(单词2)中单词1的字母数。
起初,我使用了strpos
函数,但是它似乎没有计算重复的字母,因此我改用了str_word_count
函数,但是无论word1是countex
还是5
这是我的代码:
for($i=0;$i<10 && ($rowword=mysqli_fetch_assoc($result)) ;$i++){
$aword1 = str_split($rowword['word']);
$word2=$row['word2']; //$row comes from another query that gets the word of the opponent
$countex=0;
for($i=0;$i<5;$i++){
$currentletter=$aword1[$i];
if(str_word_count($word2,0,$currentletter)){
$countex++;
}
}
} //end of outter for
有人可以告诉我是什么问题吗?
我要实现的示例:
word2 =讨厌,word1 =再次
在此示例中,countex
应该为2,因为在单词“再次”中字母“ a”和“ n”存在于单词“ annoy”中
答案 0 :(得分:1)
如果您想知道两个单词中有多少个字母,则可以使用以下代码:
$lettersFromWord1 = str_split ($word1);
$lettersFromWord2 = str_split ($word2);
$matches = 0;
foreach($lettersFromWord1 as $letter){
if ( in_array($letter, $lettersFromWord2)){
$matches++;
}
}
echo "Word: " . $word1 . " and Word: " . $word2 . " has " . $matches . " matching letters";
答案 1 :(得分:0)
您可以同时使用str_split
和strpos
:
<?php
$word1 = 'abcdefghijkl';
$word2 = 'acgikluuo';
$expected = 6;
function countMatchingChars($word1, $word2) {
$matching = 0;
foreach(str_split($word1) as $char) {
if(strpos($word2, $char) !== false) {
$matching++;
}
}
return $matching;
}
$matchingChars = countMatchingChars($word1, $word2);
assert($matchingChars === $expected);
参考文献: