Re: Counting occurances
| From: | Lars Torben Wilson | Date: | Mon, 14 Aug 2000 01:42:15 +0000 |
| Subject: | Re: Counting occurances | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-11541@lists.php.net to get a copy of this message | ||
Wizaerd writes:
> Is there a PHP function I'm missing somewhere that'll count the number of
> occurances of a substring within a string?
>
> Something such as:
>
> $cStr = "There is a cat in the house. It is a mean cat. We should shoot
> that cat.";
> $nCount = str_count( "cat", $cStr ); // would return 3
> $nCount = str_count( "o", $cStr ); // would return 4
>
> Joseph E. Sheble
> a.k.a. Wizaerd
> Wizaerd's Realm
> Canvas, 3D, Graphics, ColdFusion
> http://www.wizaerd.com
> =================================
Indeed there is, at least in PHP4:
http://www.php.net/manual/function.substr-count.php
For PHP3, the following should do what you want (I've reversed the
argument order from your example to match PHP4's argument order):
<?php
function substr_count($haystack, $needle) {
$slen = strlen($needle) - 1;
$count = 0;
while ($pos = strpos("X$haystack", $needle)) {
$haystack = substr($haystack, $pos + $slen);
$count++;
}
return $count;
}
?>
Good luck,
Torben
--
+----------------------------------------------------------------+
|Torben Wilson <torben@php.net> Netmill iTech|
|http://www.coastnet.com/~torben http://www.netmill.fi|
|Ph: 1 250 383-9735 torben@netmill.fi|
+----------------------------------------------------------------+