Forum Moderators: coopster
as example on that page shows, you will not end up replacing anything in the string, just make use of count.
You want to find "ll" , but don't want to replace it with anything ("") in this string "good golly miss molly!", and setting $count to return number of occurances
// Use of the count parameter is available as of PHP 5.0.0
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count; // 2
I am not sure if you want to be case sensitive.
Another way to do this is to separate your big string into individual stings, put them in the array, and then search array for your particular value and keeping count...
There are also few other ways to do it , utilizing only string functions or combining them with array functionality, but it really depends of how this part of the code fits with everything else.
Oh, and php.net [php.net] is your friend...
You can also use substr_count [uk3.php.net] for a string count:
$string = 'William Black Black';
echo substr_count($string, 'Black'); // 2
dc
$string = 'Mary had a a little lamb, she she tied it it it to a pylon, 3000 volts whent up its ... and turned its wool to nylon';
$words = explode(' ', $string);
$duplicates = array_unique($words);
$count = array();
foreach ($words as $word) {
foreach ($duplicates as $duplicate) {
if ($word == $duplicate) {
$count[$duplicate]++;
}
}
}
foreach ($count as $k => $v) {
if ($v > 1) {
$c = $v-1; // as a count of 1 is the first occurance
echo "$k was duplicated $c times<br />\n";
}
}
<edit>
Removed the stupid bits that I originally posted. Thats stupid code...not just stupid, in case you are wandering ;)
[edited by: PHP_Chimp at 7:19 pm (utc) on Jan. 1, 2008]