função PHP substr_count ()
Exemplos
Contar o número de "mundo" aparece em uma string:
<?php
echo substr_count("Hello world. The world is nice","world");
?>
echo substr_count("Hello world. The world is nice","world");
?>
Correndo instância »
substr_count () calcula o número de ocorrências no substring string.
Nota: substring é sensível a maiúsculas.
Nota: Esta função não conta substrings sobrepostas (ver Exemplo 2).
NOTA: Se você iniciar o argumento mais parâmetro de comprimento é maior que o comprimento da corda, a função irá gerar um aviso (ver Exemplo 3).
gramática
substr_count( string,substring,start,length )
参数 | 描述 |
---|---|
string | 必需。规定要检查的字符串。 |
substring | 必需。规定要检索的字符串。 |
start | 可选。规定在字符串中何处开始搜索。 |
length | 可选。规定搜索的长度。 |
detalhes técnicos
retorna: | Retorna o número de ocorrências no substring string. |
---|---|
versão do PHP: | 4+ |
log Update: | No PHP 5.1, adicionar os parâmetros start e length. |
mais exemplos
exemplo 1
Use 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 PHP"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is PHP"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
$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 PHP"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is PHP"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
Correndo instância »
exemplo 2
substring sobreposição:
<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
Correndo instância »
exemplo 3
Se os parâmetros de início e comprimento ao longo do comprimento da corda, da função gera um aviso:
<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
Devido ao comprimento do valor exceder o comprimento da corda (3 + 9 maior do que 12). Então, ele produzirá um aviso.
PHP seqüência de referência