self::MAX_SOURCE_BYTES ) { $text = substr( $text, 0, self::MAX_SOURCE_BYTES ); } $text = strip_shortcodes( $text ); // Elements whose content is not text for people. $text = self::replace( '@<(script|style|noscript|template|svg|iframe|object)\b[^>]*>.*?\1\s*>@is', ' ', $text ); // Block-level and line-break tags separate words: "
a
b
" is "a b". $text = self::replace( '@?(?:address|article|aside|blockquote|br|dd|div|dl|dt|figcaption|figure|footer|h[1-6]|header|hr|li|main|nav|ol|p|pre|section|table|tbody|td|tfoot|th|thead|tr|ul)\b[^>]*>@i', ' ', $text ); $text = wp_strip_all_tags( $text ); $text = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); $text = wp_check_invalid_utf8( $text, true ); // Control characters (except tab and newline, handled below). $text = self::replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $text ); // All kinds of white space, including no-break spaces, become one space. $text = self::replace( '/\s+/u', ' ', $text ); return trim( $text ); } /** * Shortens plain text to at most $limit characters, cutting at a word * boundary when there is a reasonable one and adding an ellipsis. * * @param string $text Plain text (see plain()). * @param int $limit Maximum length in characters, ellipsis included. * @return string */ public static function truncate( $text, $limit ) { $text = (string) $text; $limit = max( 2, (int) $limit ); if ( mb_strlen( $text, 'UTF-8' ) <= $limit ) { return $text; } $cut = mb_substr( $text, 0, $limit - 1, 'UTF-8' ); // If the cut fell inside a word, drop that partial word. if ( ! preg_match( '/\s/u', mb_substr( $text, $limit - 1, 1, 'UTF-8' ) ) ) { $shorter = self::replace( '/\s+\S*$/u', '', $cut ); // Only if that does not throw away most of the text (for example // Chinese or Japanese, which has no spaces). if ( mb_strlen( $shorter, 'UTF-8' ) >= (int) ( $limit * 0.6 ) ) { $cut = $shorter; } } $cut = rtrim( $cut, " \t\n\r\0\x0B.,;:!?-" ); return $cut . '…'; } /** * Runs preg_replace() but returns the subject unchanged if the engine fails * (for example on invalid UTF-8 or a backtracking limit), instead of null. * * @param string $pattern Regular expression. * @param string $replacement Replacement. * @param string $subject Subject. * @return string */ private static function replace( $pattern, $replacement, $subject ) { $result = preg_replace( $pattern, $replacement, $subject ); return is_string( $result ) ? $result : $subject; } }