It was suggested to use
substr_count ( implode( $haystackArray ), $needle );
instead of the function described previously, however this has one flaw. For example this array:
array (
0 => "mystringth",
1 => "atislong"
);
If you are counting "that", the implode version will return 1, but the function previously described will return 0.
substr_count
(PHP 4, PHP 5)
substr_count — Cuenta el número de apariciones de la subcadena
Descripción
substr_count() devuelve el número de veces que la subcadena caracter se encuentra en la cadena . La función distingue las mayúsculas y minúsculas de caracter .
Note: La función no cuenta las cadenas que se solapan. (Ver ejemplo inferior)
Lista de parámetros
- cadena
-
La cadena en la que se busca
- caracter
-
El caracter o subcadena que se busca
- comienzo
-
La posición en la que se empieza a contar
- longitud
-
La máxima longitud desde la posición de comienzo en la que se busca la subcadena. Se produce un aviso si la suma del commienzo y la longitud es mayor que la longitud de cadena .
Valores retornados
La función devuelve un variable de tipo integer.
Registro de cambios
| Versión | Descripción |
|---|---|
| 5.1.0 | Se incluyen los parametros comienzo y longitud |
Ejemplos
Example #1 Ejemplo de substr_count()
<?php
$text = 'This is a test';
echo strlen($text); // Salida = 14
echo substr_count($text, 'is'); // Salida = 2
// la cadena de busqueda se reduce a 's is a test', por lo que el resultado es 1
echo substr_count($text, 'is', 3);
// la cadena de busqueda se reduce a 's i', por lo que el resultado es 0
echo substr_count($text, 'is', 3, 3);
// se muestra un mensaje de advertencia, ya que 5+10 > 14
echo substr_count($text, 'is', 5, 10);
// el resultado es solo 1, ya que no se tienen en cuenta las subcadenas que se solapan
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>
Ver también
- count_chars() - Devuelve información sobre los caracteres usados en una cadena
- strpos() - Encuentra la posición de la primera aparición de una cadena
- substr() - Devuelve parte de una cadena
- strstr() - Encuentra la primera aparición de una cadena
substr_count
18-Jun-2009 08:37
23-Mar-2009 09:53
For some who seeked for an easy way to resolve URL composed of /../ like http://w3.host.tld/path/to/the/file/../../file.extension, here is a solution
<?php
$url = 'http://w3.host.tld/path/to/file/../file.extension';
while (substr_count($url, "../"))
{
$url = preg_replace('#/[^/]+/\.\.#', '', $url);
}
//outputs 'http://w3.host.tld/path/to/file.extension'
?>
and seems to work perfectly!
12-Jan-2009 04:17
below was suggested a function for substr_count'ing an array, yet for a simpler procedure, use the following:
<?php
substr_count ( implode( $haystackArray ), $needle );
?>
11-Jul-2008 01:49
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
?>
24-Jul-2007 01: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.)
05-May-2007 11: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;
}
?>
26-Oct-2006 02: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))
21-Dec-2003 09: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.
