Count occurrences of a word in string
Jump to navigation
Jump to search
Count occurrences of a word in string
Excel
- Using the function SUBSTITUTE & LEN functions. demo. Or
- Using the function COUNTIF
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;
-- Count occurrences of a string: . SET @input = "www.google.com"; SET @separator = "."; SELECT (LENGTH(@input ) - LENGTH(REPLACE(@input , @separator, ""))) / LENGTH(@separator) AS count_of_separator; -- expected result: 2 -- Count occurrences of a string: og SET @input = "www.google.com"; SET @separator = "og"; SELECT (LENGTH(@input ) - LENGTH(REPLACE(@input , @separator, ""))) / LENGTH(@separator) AS count_of_separator; -- expected result: 1
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);
References
- mysql - Count the number of occurences of a string in a VARCHAR field? - Stack Overflow [Last visited: 2016-09-21]