MDL-46256 count_words: fix handling of paragraphs

This commit is contained in:
Tim Hunt
2021-01-21 09:54:36 +00:00
parent 509eef8fcf
commit 8321e49c8a
2 changed files with 33 additions and 2 deletions
+18 -1
View File
@@ -8375,10 +8375,27 @@ function moodle_setlocale($locale='') {
* Words are defined as things between whitespace.
*
* @category string
* @param string $string The text to be searched for words.
* @param string $string The text to be searched for words. May be HTML.
* @return int The count of words in the specified string
*/
function count_words($string) {
// Before stripping tags, add a space after the close tag of anything that is not obviously inline.
// Also, br is a special case because it definitely delimits a word, but has no close tag.
$string = preg_replace('~
( # Capture the tag we match.
</ # Start of close tag.
(?! # Do not match any of these specific close tag names.
a> | b> | del> | em> | i> |
ins> | s> | small> |
strong> | sub> | sup> | u>
)
\w+ # But, apart from those execptions, match any tag name.
> # End of close tag.
|
<br> | <br\s*/> # Special cases that are not close tags.
)
~x', '$1 ', $string); // Add a space after the close tag.
// Now remove HTML tags.
$string = strip_tags($string);
// Decode HTML entities.
$string = html_entity_decode($string);