downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

substr_replace> <substr_compare
[edit] Last updated: Fri, 17 May 2013

view this page in

substr_count

(PHP 4, PHP 5)

substr_countCuenta el número de apariciones del substring

Descripción

int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )

substr_count() devuelve el número de veces en que el substring needle aparece en el string haystack. Por favor nótese que needle es sensible a mayúsculas y minúsculas.

Nota:

Esta función no cuenta los substrings que se solapan. Véase el ejemplo de abajo!

Parámetros

haystack

El string dentro del cual buscar

needle

El substring a buscar

offset

El desplazamiento por dónde empezar a contar

length

La longitud máxima después del desplazamiento especificado para buscar el substring. Se emite una advertencia si offset más length es mayor que la longitud de haystack.

Valores devueltos

Esta función devuelve un integer.

Historial de cambios

Versión Descripción
5.1.0 Los parámetros offset y length fueron agregados

Ejemplos

Ejemplo #1 Ejemplo de substr_count()

<?php
$text 
'This is a test';
echo 
strlen($text); // 14

echo substr_count($text'is'); // 2

// el string es reducido a 's is a test', así que muestra 1
echo substr_count($text'is'3);

// el texto es reducido a 's i', así que muestra 0
echo substr_count($text'is'33);

// genera una advertencia debido a que 5+10 > 14
echo substr_count($text'is'510);


// muestra sólo 1, debido a que no cuenta substrings solapados.
$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 ocurrencia de un substring en un string
  • substr() - Devuelve parte de una cadena
  • strstr() - Encuentra la primera aparición de un string



substr_replace> <substr_compare
[edit] Last updated: Fri, 17 May 2013
 
add a note add a note User Contributed Notes substr_count - [10 notes]
up
4
jrhodes at roket-enterprises dot com
3 years ago
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.
up
2
info at fat-fish dot co dot il
6 years ago
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;
}
?>
up
0
XinfoX X at X XkarlX X-X XphilippX X dot X XdeX
9 years ago
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.
up
-1
chrisstocktonaz at gmail dot com
3 years ago
In regards to anyone thinking of using code contributed by zmindster at gmail dot com

Please take careful consideration of possible edge cases with that regex, in example:

$url = 'http://w3.host.tld/path/to/file/..../file.extension';
$url = 'http://w3.host.tld/path/to/file/../file.extension?malicous=....';

This would cause a infinite loop and for example be a possible entry point for a denial of service attack. A correct fix would require additional code, a quick hack would be just adding a additional check, without clarity or performance in mind:

...
$i = 0;
while (substr_count($url, '../') && ++$i < strlen($url))
...

-Chris
up
0
Douglas Dennis
22 days ago
It was previously noted that if you use "substr_count(implode(array))" with this array:

array (
  0 => "mystringth",
  1 => "atislong"
);

The following would result:
"If you are counting "that", the implode version will return 1, but the function previously described will return 0."

You can fix this by using substr_count(implode(' ', array), 'that') which will result in the following string: "mystringth atislong".
up
0
gigi at phpmycoder dot com
4 years ago
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 );
?>
up
0
danjr33 at gmail dot com
5 years ago
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.)
up
0
flobi at flobi dot com
6 years ago
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))
up
-1
Anonymous
4 years ago
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
?>
up
-2
zmindster at gmail dot com
4 years ago
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!

 
show source | credits | stats | sitemap | contact | advertising | mirror sites