PHP Doku:: Ermittelt, wie oft eine Zeichenkette in einem String vorkommt - function.substr-count.html

Verlauf / Chronik / History: (11) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzTextverarbeitungZeichenkettenString-Funktionensubstr_count

Ein Service von Reinhard Neidl - Webprogrammierung.

String-Funktionen

<<substr_compare

substr_replace>>

substr_count

(PHP 4, PHP 5)

substr_count Ermittelt, wie oft eine Zeichenkette in einem String vorkommt

Beschreibung

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

Die Funktion substr_count() ermittelt, wie oft needle in dem String haystack vorkommt, und gibt die Anzahl der Vorkommen zurück. Beachten Sie, dass der Parameter needle case sensitive ist.

Hinweis:

Die Funktion zählt einander überlappende Substrings nicht mit. Beachten Sie das untenstehende Beispiel!

Parameter-Liste

haystack

Der String, in dem gesucht werden soll

needle

Der Substring, nach dem gesucht werden soll

offset

Die Zeichenposition, an der die Zählung begonnen werden soll

length

Die maximale Länge nach dem angegebenen Offset, in der nach dem Substring gesucht werden soll. Es wird eine Warnung ausgegeben, wenn Offset plus Länge größer als die Länge von haystack sind.

Rückgabewerte

Die Funktion gibt einen Wert vom Typ integer zurück.

Changelog

Version Beschreibung
5.1.0 Hinzufügen der Parameter offset und length

Beispiele

Beispiel #1 Ein substr_count() Beispiel

<?php
$text 
'Dies ist ein Test';
echo 
strlen($text); // 17

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

// wird der String auf 's ist ein Test' reduziert,
// lautet das ausgegebene Ergebnis 1
echo substr_count($text'es'3);

// wird der String auf 's i' reduziert,
// lautet das Ergebnis 0
echo substr_count($text'es'33);

// generiert eine Warnung, da 5+13 > 17
echo substr_count($text'es'513);


// gibt 1 aus, da überlappende Substrings nicht gezählt werden
$text2 'gcdgcdgcd';
echo 
substr_count($text2'gcdgcd');
?>

Siehe auch

  • count_chars() - Gibt Informationen über die in einem String enthaltenen Zeichen zurück
  • strpos() - Sucht das erste Vorkommen des Suchstrings
  • substr() - Gibt einen Teil eines Strings zurück
  • strstr() - Findet das erste Vorkommen eines Strings


9 BenutzerBeiträge:
- Beiträge aktualisieren...
chrisstocktonaz at gmail dot com
27.08.2009 1:52
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
jrhodes at roket-enterprises dot com
18.06.2009 10:37
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.
zmindster at gmail dot com
23.03.2009 22: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!
gigi at phpmycoder dot com
12.01.2009 17: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 );
?>
Anonymous
11.07.2008 15: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
?>
danjr33 at gmail dot com
24.07.2007 15: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
6.05.2007 1: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
26.10.2006 4: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.12.2003 22: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.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)