Difference between revisions of "Count occurrences of a word in string"

From LemonWiki共筆
Jump to: navigation, search
m (PHP)
m (MySQL way)
Line 11: Line 11:
  
 
SELECT FLOOR((LENGTH(@paragraph) - LENGTH(REPLACE(@paragraph, @term, ''))) / LENGTH(@term)) AS occurrences;
 
SELECT FLOOR((LENGTH(@paragraph) - LENGTH(REPLACE(@paragraph, @term, ''))) / LENGTH(@term)) AS occurrences;
 +
 +
/* same with the following query */
 +
SELECT FLOOR((CHAR_LENGTH(@paragraph) - CHAR_LENGTH(REPLACE(@paragraph, @term, ''))) / CHAR_LENGTH(@term)) AS occurrences;
 
</pre>
 
</pre>
 +
 +
[http://sqlfiddle.com/#!9/6d06f/480/2 online example]
  
 
== PHP ==
 
== PHP ==

Revision as of 19:01, 9 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;

/* same with the following query */
SELECT FLOOR((CHAR_LENGTH(@paragraph) - CHAR_LENGTH(REPLACE(@paragraph, @term, ''))) / CHAR_LENGTH(@term)) AS occurrences;

online example

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);