Count occurrences of a word in string

From LemonWiki共筆
Revision as of 20:34, 7 August 2019 by Planetoid (talk | contribs) (→‎PHP)
Jump to navigation Jump to search

Count occurrences of a word in string

Excel

Using the function SUBSTITUTE & LEN functions. demo

MySQL way

SET @paragraph := 'an apple a day keeps the doctor away';
SET @term := 'apple';

SELECT FLOOR((LENGTH(@paragraph) - LENGTH(REPLACE(@paragraph, @term, ''))) / LENGTH(@term)) AS occurrences;

PHP

Using the mb_substr_count (binary safe) or substr_count functions. See details on demo.


$input = 'an apple a day keeps the doctor away';
$term = 'apple';

echo substr_count($input, $term);