views:

233

answers:

1

In a string like "abc fox fox fox ghi xyz" how can i get the number of times 'fox' is repeated in the string?

+4  A: 
$string = 'abc fox fox fox ghi xyz';

$substring = 'fox';

$substringCount = substr_count($string, $substring);

echo '"' . $substring . '" appears in "' . $string . '" ' . $substringCount . ' times';
alex
Aaah. beat me to it. :)
Paolo Bergantino
That's a first Paolo!! :)
alex
There's a builtin for that? Wow! Named differently from every other string function, I presume! ;)
Lucas Jones
PHP consistency can be a bit tricky sometimes... but php.net is only a few clicks away 99% of the time :)
alex
found this function today, was hard to find, not being next to the str* or str_* functions
Phil Carter
Ha! substringCount! That's awesome, a very elegant way to do it.
jsims281