PHP 如何统计字符串中的字母组成单词的次数?

PHP How to count the number of times you can make a word from letters in string?

我想做一个功能,你可以看到你可以从文本中随机生成单词多少次。

例如:

正文是:火腿跟着现在欣喜若狂使用口语练习可能会重复。他自己很明显哦,我非常关心他。它允许在其中普遍享受。呼吁观察谁按下提高他的。可连接仪却丝毫没有影响他不动的喜好。宣布说男孩预防措施不受影响难度改变他。

我想知道你能写多少次"potato"这个词。

所以,我开始做一个功能(当然还不够好):

<?php
$text = "Ham followed now ecstatic use speaking exercise may repeated.
Himself he evident oh greatly my on inhabit general concern. It allowance 
prevailed enjoyment in it. Calling observe for who pressed raising his. Can 
connection instrument astonished unaffected his motionless preference. 
Announcing say boy precaution unaffected difficulty alteration him.";
$word = "Potato";

//function
    function count($text) {
 for ($i = 0; $i <= strlen($text); $i++) {
  if ($text[$i] == "p") {
$p = 0;
$p++;
echo $p; } } }
?>

我现在的问题是:你怎么算从现在开始你能造出这个词"potato"的次数?

感谢您的回复。

此函数可帮助您获取 paroto 在该字符串中使用了多少次

echo substr_count($text, $word);

我的方法是遍历将每个字符存储在字典中的文本,其中键是字母,值是文本中出现的次数。处理完文本后,您可以计算出拼写 potato

的次数

首先,您不能声明 count 函数,因为它已经声明了。

试试这个:

function countt($text, $word, $count = 0) {
    $found = '';
    for($i=0; $i<strlen($word);$i++){
        for($j=0; $j<strlen($text);$j++){
            if($word{$i} === $text{$j}){
                $text = substr($text,0,$j).substr($text,$j+1);
                $found.= $word{$i};
                if($found === $word){
                    $count++;
                    return countt($text,$word,$count);
                }
                break;
            }
        }
    }
    return $count;
}

echo countt($text,'potato');//6

说明:函数查找文本中单词的每个字母的出现并将其从文本中删除。一旦它完成了与搜索到的单词相同的新单词,它就会用新文本再次调用此函数,这会错过那些使用过的字母,直到没有更多的字母可以完成另一个单词。

你可以在这里玩:

http://sandbox.onlinephpfunctions.com/code/ba579be33a82a6abdc0fc285cc4a631186eb7b29