搜索一个单词中的字母是否在另一个单词PHP字符串中找到


Searching if letters in a word are found in another word PHP Strings

正如这篇文章的标题所说,我希望能够检查一个单词的每个字母是否都在另一个单词中找到。到目前为止,这些是我能够想出的代码行:

<?php   
        $DBword = $_POST['DBword'];
        $inputWords = $_POST['inputWords'];
        $inputCount = str_word_count($inputWords,1);

        echo "<b>THE WORD:</b>"."<br/>".$DBword."<br/><br/>";
        echo "<b>WORDS ENTERED:</b><br/>";
            foreach($inputCount as $outputWords)
            {
                echo $outputWords."<br/>";
            }
            foreach($inputCount as $countWords)
            {
                for($i=0; $i<strlen($countWords); $i++)
                {$count = strpos( "$DBword", $countWords[$i]);}
                if($count === false)
                {
                    $score++;
                }

            }
            echo "<b><br/>TOTAL SCORE: </b>";
            echo $score;

        ?>

我把foreach$outputWords放在一起的目的是只输出输入的字母。至于另一个有$countWordsforeach,我用它来真正检查输入单词中的所有字母是否都在$DBword中找到。我使用for循环来检查每个字母。

到目前为止,我没有得到我想要的输出,我只是没有想法了。有什么想法吗?

function contains_letters($word1, $word2) {
  for ($i = 0; $i < strlen($word1); $i++)
    if (strpos($word2, $word1{$i}) === false)
      return false;
  return true;
}
//example usage
if (contains_letters($_POST['inputWords'], $_POST['DBword']))
  echo "All the letters were found.";

如果此检查不区分大小写(即"A"算作"A"的用法),请将strpos更改为stripos

由于要为$countWords中的每个字母覆盖for循环中的$count,因此$count将仅包含$countWord的最后一个字母的位置。此外,我不知道为什么你在没有找到字母的情况下增加分数。

无论如何,你让你的生活变得更加困难
PHP有一个计算字符串中字符数的函数:

return count_chars($dbWord, 3) === count_chars($inputWord, 3);

如果在两个字符串中都找到相同的字母,将返回true。

查找所有字母完全相同的单词的示例:

$dbWord = count_chars('foobar', 3);
$inputWords = 'barf boo oof raboof boarfo xyz';
print_r(
    array_filter(
        str_word_count($inputWords, 1),
        function($inputWord) use ($dbWord) {
            return count_chars($inputWord, 3) === $dbWord;
        }
    )
);

将只输出"raboof"answers"boarfo"。