Funkcja PHP substr_count()
Przykład
Policz, ile razy słowo „world” występuje w ciągu:
<?php
echo substr_count("Hello world. The world is nice","world");
?>
Funkcja substr_count() zlicza, ile razy podciąg występuje w ciągu.
Uwaga: w podciągu rozróżniana jest wielkość liter.
Uwaga: Ta funkcja nie zlicza nakładających się podciągów (patrz przykład 2).
Uwaga: Ta funkcja generuje ostrzeżenie, jeśli parametr początkowy plus parametr długości jest większy niż długość ciągu (patrz przykład 3).
Składnia
substr_count(string,substring,start,length)
Wartości parametrów
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 |
Szczegóły techniczne
Wartość zwrotu: | Zwraca liczbę wystąpień podciągu w ciągu |
---|---|
Wersja PHP: | 4+ |
Dziennik zmian: | PHP 7.1 - Parametrami długości mogą być 0 lub liczba ujemna. PHP 7.1 - Parametry startowe mogą być liczbą ujemną. PHP 5.1 - Dodano parametry początku i długości . |
Więcej przykładów
Przykład
Używając wszystkich parametrów:
<?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"
?>
Przykład
Nakładające się podciągi:
<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
Przykład
Jeśli parametry start i length przekraczają długość ciągu, ta funkcja wygeneruje ostrzeżenie:
<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
Spowoduje to wyświetlenie ostrzeżenia, ponieważ wartość długości przekracza długość ciągu (3+9 jest większe niż 12)
❮ Odniesienie do ciągów PHP