Count occurrences of a word in string: Difference between revisions
Jump to navigation
Jump to search
(+ PHP) |
m (→PHP) |
||
| Line 14: | Line 14: | ||
== PHP == | == PHP == | ||
Using the [https://www.php.net/manual/en/function.mb-substr-count.php mb_substr_count] ('''binary safe''') or [https://www.php.net/manual/en/function.substr-count.php substr_count] | Using the [https://www.php.net/manual/en/function.mb-substr-count.php mb_substr_count] ('''binary safe''') or [https://www.php.net/manual/en/function.substr-count.php substr_count] functions. See details on [http://sandbox.onlinephpfunctions.com/code/326ff9f24ebfea9f67ddf2f1475a6172cdcd2e66 demo]. | ||
<pre> | |||
$input = 'an apple a day keeps the doctor away'; | |||
$term = 'apple'; | |||
echo substr_count($input, $term); | |||
</pre> | |||
[[Category:Software]] [[Category:Programming]] [[Category:Data Science]] [[Category:Text file processing]] | [[Category:Software]] [[Category:Programming]] [[Category:Data Science]] [[Category:Text file processing]] | ||
Revision as of 20:34, 7 August 2019
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);