It should be noted that unlike the other substr functions, the offset value cannot be a negative value.
<?php
echo substr_count('abcdefg', 'efg', 4, 3); // 1
echo substr_count('abcdefg', 'efg', -3, 3); // warning
?>
substr_count
(PHP 4, PHP 5)
substr_count — Возвращает число вхождений подстроки
Описание
int substr_count
( string $haystack
, string $needle
)
substr_count() Возвращает число вхождений подстроки needle в строку haystack . Заметьте, что поиск ведется с учетом регистра символов.
Пример #1 Пример использования substr_count()
<?php
echo substr_count("This is a test", "is"); // 2
?>
См. также описание функций count_chars(), strpos(), substr() и strstr().
substr_count
Anonymous
11-Jul-2008 06:49
11-Jul-2008 06:49
danjr33 at gmail dot com
24-Jul-2007 06:37
24-Jul-2007 06:37
I ran into trouble using this function when I moved a script from a server with PHP5 to a server with only PHP4.
As the last two parameters were added with 5.1.0, I wrote a substitute function:
<?php
function substr_count5($str,$search,$offset,$len) {
return substr_count(substr($str,$offset,$len),$search);
}
?>
Use it exactly as substr_count() is used in PHP5. (This will work in PHP5 as well.)
info at fat-fish dot co dot il
05-May-2007 04:07
05-May-2007 04:07
a simple version for an array needle (multiply sub-strings):
<?php
function substr_count_array( $haystack, $needle ) {
$count = 0;
foreach ($needle as $substring) {
$count += substr_count( $haystack, $substring);
}
return $count;
}
?>
flobi at flobi dot com
25-Oct-2006 07:07
25-Oct-2006 07:07
Making this case insensitive is easy for anyone who needs this. Simply convert the haystack and the needle to the same case (upper or lower).
substr_count(strtoupper($haystack), strtoupper($needle))
XinfoX X at X XkarlX X-X XphilippX X dot X XdeX
21-Dec-2003 01:27
21-Dec-2003 01:27
Yet another reference to the "cgcgcgcgcgcgc" example posted by "chris at pecoraro dot net":
Your request can be fulfilled with the Perl compatible regular expressions and their lookahead and lookbehind features.
The example
$number_of_full_pattern = preg_match_all('/(cgc)/', "cgcgcgcgcgcgcg", $chunks);
works like the substr_count function. The variable $number_of_full_pattern has the value 3, because the default behavior of Perl compatible regular expressions is to consume the characters of the string subject that were matched by the (sub)pattern. That is, the pointer will be moved to the end of the matched substring.
But we can use the lookahead feature that disables the moving of the pointer:
$number_of_full_pattern = preg_match_all('/(cg(?=c))/', "cgcgcgcgcgcgcg", $chunks);
In this case the variable $number_of_full_pattern has the value 6.
Firstly a string "cg" will be matched and the pointer will be moved to the end of this string. Then the regular expression looks ahead whether a 'c' can be matched. Despite of the occurence of the character 'c' the pointer is not moved.
