| User Contributed Notes: substr_count |
calo@iquebec.com
28-Oct-2000 03:42 |
This fonction do the same thing that substr_count(). It is useful when working with PHP3.
function substr_count($haystack, $needle, $offset = 0) {
$i = 0;
$count = 0;
while ($i==0) {
$longueur = strlen($haystack);
$position = strpos($haystack, $needle, $offset);
if ($position && ($offset + strlen($needle)) < $longueur) {
$offset = $position+strlen($needle);
$count++;
} else {
$i++;
}
}
return $count;
}
|
|
ender@sbox.tu-graz.ac.at
02-Nov-2000 06:18 |
that's true, but your function substr_count () has a big BUG in it. if the $haystack starts with an occurence of $needle the algorithm fails.
|
|
amir@browse.co.uk
05-Nov-2000 07:38 |
I wanted to count the total number of string occurances within a text file, using PHP3. I was looking for the total occurances of two strings, 'a1' and 'a2'. Here's how I did it:
<?php
// Open the text file
$filename = "../log.txt";
$fp = fopen($filename,"r");
// Read the file
$haystack = fread($fp,filesize($filename));
// Define search
$needle1 = "a1";
$needle2 = "a2";
// Count the number of occurences
$num_occurs1 = count(explode($needle1,$haystack)) - 1;
$num_occurs2 = count(explode($needle2,$haystack)) - 1;
// Set the total number of occurences
$total1 = $num_occurs1;
$total2 = $num_occurs2;
?>
|
|
lordwo@wanadoo.fr
02-Dec-2000 06:59 |
Instead using the precedent fonction posted by (don't remind).
$strg is the main string.
$srch is the string to count in $strg.
Note this function support when youve got the string "aah !" and you try to count "a".
Support/Feedback : lordwo@wanadoo.fr
function strcount ($strg,$srch) {
$i = 0;
while ($i == 0) :
$n = strpos ($strg, $srch);
if($n != $false) {
$o++;
$strg = substr($strg,$n + 1);
}
if ($n == $false) {
if ( substr($strg,0,1) != $srch ) {
$i++;
}
else {
$o++;
$strg = substr($strg,$n + 1);
}
}
endwhile;
return $o;
}
|
|
kirill@uptilt.com
20-Dec-2000 12:42 |
Note that substr_count is case sensitive! So "NEEDLE" wont be counted. Use ereg functions.
|
|
Jesse@bend.com
08-Jan-2001 07:58 |
I am not certain why the above fellah is worried about case sensitivity, ereg functions are mighty slow.. and if you need a case insensitive count, try this:
substr_count(strtolower($haystack), strtolower($needle))
|
|
hazelnutlatte@hotmail.com
24-Jan-2001 04:17 |
Both of the posted functions that are supposed to work with PHP3 don't return the right count if $needle is the first word in $haystack. Workaround (if $haystack is generated dynamically): tack a dummy word onto the beginning of $haystack.
|
|
webmaster@lynucs.com
07-Feb-2001 06:42 |
Hey guys.... Look this :
function substr_count($string,$search) {
$temp = str_replace($search,$search."a",$string);
return strlen($temp)-strlen($string);
}
Sylvinus
|
|
dhp@atek.cc
22-Feb-2001 09:41 |
To Sylvinus;
I make a power search engine only with your function. This engine use a CSV file. Thanks a lot !
|
|