A
A
apaicer2018-04-06 15:57:29
PHP
apaicer, 2018-04-06 15:57:29

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");

Can someone write how to use the function and explain a little?
Thanks in advance.
It was given as a hint.
```php
function countChars ($text, $char) {
// your code
return $resultText;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeniy Odinets, 2018-04-06
@apaicer

$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);
}

M
Maxim Osadchy, 2018-04-06
@waspmax1

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 question

Ask a Question

731 491 924 answers to any question