diff -u b/core/lib/Drupal/Component/Utility/SafeMarkup.php b/core/lib/Drupal/Component/Utility/SafeMarkup.php --- b/core/lib/Drupal/Component/Utility/SafeMarkup.php +++ b/core/lib/Drupal/Component/Utility/SafeMarkup.php @@ -330,34 +330,44 @@ } /** - * Truncates an HTML string safely to a number of text characters. + * Truncates an HTML string safely to a number of rendered text characters. * * Functions similarly to \Drupal\Component\Utility\Unicode::truncate(), - * but strips HTML tags prior to truncating and ensures the truncated string - * has well-formed HTML entities. + * but strips HTML tags prior to truncating and counts HTML entities (e.g., + * '&') as a single character. + * + * This function is intended for use on output, when it is desired to + * view truncated plain text (e.g., log messages in a list) in an HTML + * display. Because HTML entities are encoded after truncation, the + * returned string may contain more string characters than $max_length, so + * this is not a reliable function to use for truncating strings to a + * storage imposed maximum length. * * @param string $string - * The string to truncate. HTML tags are stripped prior to truncation, but - * HTML entities that fit in the output length are preserved. + * The string to truncate. HTML tags are stripped prior to truncation. HTML + * entities are decoded prior to truncation and re-encoded after. * @param int $max_length - * An upper limit on the returned string length, including trailing ellipsis - * if $add_ellipsis is TRUE. + * An upper limit on the returned text length when viewed as HTML, + * including trailing ellipsis if $add_ellipsis is TRUE. For purposes of + * this limit, each HTML entity is counted as a single character, so the + * returned string length may be longer. * @param bool $wordsafe * If TRUE, attempt to truncate on a word boundary. See Unicode::truncate() * for details. * @param bool $add_ellipsis * If TRUE, add '...' to the end of the truncated string (defaults to - * FALSE). The string length will still fall within $max_length. + * FALSE). The text length will still fall within $max_length. * @param int $min_wordsafe_length * If $wordsafe is TRUE, the minimum acceptable length for truncation (before * adding an ellipsis, if $add_ellipsis is TRUE). See Unicode::truncate() * for details. * * @return string - * The truncated string. + * The truncated string, encoded for HTML display. */ public static function truncate($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1) { - // Strip tags prior to truncation, so that the output has useful text. + // Strip tags prior to truncation, so that truncation doesn't need to + // handle unclosed tags, and retains the maximum allowable text characters. $string = strip_tags($string); // Decode entities, so that truncation sees them as a single character.