substr_count

(PHP 4, PHP 5, PHP 7)

substr_countConta o número de ocorrências de uma substring

Descrição

substr_count ( string $haystack , string $needle [, int $offset [, int $length ]] ) : int

substr_count() retorna o número de vezes que a substring needle ocorre na string. Note que needle faz distinção de maiúscula e minúscula.

Nota:

Esta função não conta substrings sobrepostas. Veja o exemplo abaixo!

Parâmetros

haystack

A string onde será feita a busca

needle

A substring a ser procurada

offset

O índice onde inicia a contagem

length

O valor máximo depois do índice especificado para buscar pela substring. Mostra um aviso se o tamanho do índice for maior que o tamanho de haystack.

Valor Retornado

Esta função retorna um integer.

Changelog

Versão Descrição
7.1.0 Support for negative offsets and lengths has been added. length may also be 0 now.

Exemplos

Exemplo #1 Exemplo da substr_count()

<?php
$text 
'This is a test';
echo 
strlen($text); // 14

echo substr_count($text'is'); // 2

// the string is reduced to 's is a test', so it prints 1
echo substr_count($text'is'3);

// the text is reduced to 's i', so it prints 0
echo substr_count($text'is'33);

// generates a warning because 5+10 > 14
echo substr_count($text'is'510);


// prints only 1, because it doesn't count overlapped subtrings
$text2 'gcdgcdgcd';
echo 
substr_count($text2'gcdgcd');
?>

Veja Também

  • count_chars() - Retorna informações sobre os caracteres usados numa string
  • strpos() - Encontra a posição da primeira ocorrência de uma string
  • substr() - Retorna uma parte de uma string
  • strstr() - Encontra a primeira ocorrencia de uma string