Função PHP substr_count()
Exemplo
Conte o número de vezes que "world" ocorre na string:
<?php
echo substr_count("Hello world. The world is nice","world");
?>
A função substr_count() conta o número de vezes que uma substring ocorre em uma string.
Nota: A substring faz distinção entre maiúsculas e minúsculas.
Nota: Esta função não conta substrings sobrepostas (veja o exemplo 2).
Nota: Esta função gera um aviso se o parâmetro start mais o parâmetro length for maior que o comprimento da string (veja o exemplo 3).
Sintaxe
substr_count(string,substring,start,length)
Valores de parâmetro
Parameter | Description |
---|---|
string | Required. Specifies the string to check |
substring | Required. Specifies the string to search for |
start | Optional. Specifies where in string to start searching. If negative, it starts counting from the end of the string |
length | Optional. Specifies the length of the search |
Detalhes técnicos
Valor de retorno: | Retorna o número de vezes que a substring ocorre na string |
---|---|
Versão do PHP: | 4+ |
Registro de alterações: | PHP 7.1 - Os parâmetros de comprimento podem ser 0 ou um número negativo. PHP 7.1 - Os parâmetros de início podem ser um número negativo. PHP 5.1 - Os parâmetros start e length foram adicionados. |
Mais exemplos
Exemplo
Usando todos os parâmetros:
<?php
$str = "This is nice";
echo strlen($str)."<br>"; // Using strlen() to return the string length
echo substr_count($str,"is")."<br>"; // The number of times "is" occurs in the string
echo substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is nice"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is nice"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
Exemplo
Substrings sobrepostas:
<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
Exemplo
Se os parâmetros start e length excederem o comprimento da string, esta função emitirá um aviso:
<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
Isso gerará um aviso porque o valor do comprimento excede o comprimento da string (3 + 9 é maior que 12)
❮ Referência de String PHP