I wanted to make a function which you can see how many times you can make a given word from a text.
For example:
The text is: 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.
$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";
I want to know how many times you can write the word "potato". The expected count is 6
times.
I started with something like this:
function count($text) {
for ($i = 0; $i <= strlen($text); $i++) {
if ($text[$i] == "p") {
$p = 0;
$p++;
echo $p;
}
}
}
Firstly, you cannot redeclare a
count()
function -- it is already declared as a native function in PHP.Try this recursive function which contains nested loops:
Explanation: This recursive function finds occurrences of each letter of a word in text and removes it from the text. Once it completes the new word that is identical to the searched one, it calls this function again with new text, that misses those used letters, until there is no more letters left that could complete another word.
You can play with it here: https://3v4l.org/h43rq