Answer the question
In order to leave comments, you need to log in
How to write a function?
Good afternoon! Here is the condition: the function receives text in the $text variable and a letter in the $char variable. Implement a function that counts how many times a given letter occurs in the text, if more than one character comes to the char variable, return the value -1.
I can only do this.
$text = "Text oppa post lost kost most dust past";
$char = "p";
echo substr_count("$text", "$char");
Answer the question
In order to leave comments, you need to log in
$text = "Text oppa post lost kost most dust past";
$char = "p";
echo countChars($text, 'p'); // => 4
echo countChars($text, 'pp'); // => -1
echo countChars($text, $char); // => 4
function countChars($text, $char) {
if (mb_strlen ($char) > 1) {
return -1;
}
return substr_count($text, $char);
}
function my_substr_count(string $text, string $char):int
{
if(strlen($char) > 1){
return -1;
}
$re = "/($char)/";
preg_match_all($re, $text, $matches, PREG_SET_ORDER, 0);
return count($matches);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question