How to get the number of repetitions of a string in PHP

In a line like this "abc fox fox fox ghi xyz"

, how can I get the number of times "fox" is repeated in the line?

+1


a source to share


2 answers


$string = 'abc fox fox fox ghi xyz';

$substring = 'fox';

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

echo '"' . $substring . '" appears in "' . $string . '" ' . $substringCount . ' times';

      



+7


a source


The method is substr_count()

really very nice, but if you have more needs (for example, to match only whole words), here is a regex using preg_match_all()

word boundaries as well:

$nb_of_matches = preg_match_all('/\bfox\b/', $subject);

      



Pretty simple :-)

0


a source







All Articles