PHP substr_count() Funzione
❮ Riferimento alla stringa PHP
Esempio
Conta il numero di volte in cui "mondo" compare nella stringa:
<?php
echo substr_count("Hello world. The world is nice","world");
?>
La funzione substr_count() conta il numero di volte in cui una sottostringa si verifica in una stringa.
Nota: la sottostringa fa distinzione tra maiuscole e minuscole.
Nota: questa funzione non conta le sottostringhe sovrapposte (vedi esempio 2).
Nota: questa funzione genera un avviso se il parametro di avvio più il parametro di lunghezza è maggiore della lunghezza della stringa (vedi esempio 3).
Sintassi
substr_count(string,substring,start,length)
Valori dei parametri
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 |
Dettagli tecnici
Valore di ritorno: | Restituisce il numero di volte in cui la sottostringa si verifica nella stringa |
---|---|
Versione PHP: | 4+ |
Registro delle modifiche: | PHP 7.1 - I parametri di lunghezza possono essere 0 o un numero negativo. PHP 7.1 - I parametri di partenza possono essere un numero negativo. PHP 5.1 - Sono stati aggiunti i parametri di inizio e lunghezza . |
Altri esempi
Esempio
Utilizzando tutti i parametri:
<?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"
?>
Esempio
Sottostringhe sovrapposte:
<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
Esempio
Se i parametri di inizio e lunghezza superano la lunghezza della stringa, questa funzione emetterà un avviso:
<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
Questo genererà un avviso perché il valore della lunghezza supera la lunghezza della stringa (3+9 è maggiore di 12)
❮ Riferimento alla stringa PHP