In a string like "abc fox fox fox ghi xyz"
how can i get the number of times 'fox' is repeated in the string?
views:
233answers:
1
+4
A:
$string = 'abc fox fox fox ghi xyz';
$substring = 'fox';
$substringCount = substr_count($string, $substring);
echo '"' . $substring . '" appears in "' . $string . '" ' . $substringCount . ' times';
alex
2009-05-21 21:49:11
Aaah. beat me to it. :)
Paolo Bergantino
2009-05-21 21:50:13
That's a first Paolo!! :)
alex
2009-05-21 21:50:33
There's a builtin for that? Wow! Named differently from every other string function, I presume! ;)
Lucas Jones
2009-05-21 21:51:33
PHP consistency can be a bit tricky sometimes... but php.net is only a few clicks away 99% of the time :)
alex
2009-05-21 21:53:17
found this function today, was hard to find, not being next to the str* or str_* functions
Phil Carter
2009-05-21 21:54:11
Ha! substringCount! That's awesome, a very elegant way to do it.
jsims281
2009-05-22 16:03:55