wp_html_excerpt()WP 2.5.0

Safely extracts not more than the first $count characters from HTML string.

UTF-8, tags and entities safe prefix extraction. Entities inside will NOT be counted as one character. For example & will be counted as 4, < as
3, etc.

1 time — 0.0000191 sec (very fast) | 50000 times — 0.10 sec (speed of light) | PHP 7.4.25, WP 6.0.1

No Hooks.

Return

String. The excerpt.

Usage

wp_html_excerpt( $str, $count, $more );
$str(string) (required)
String to get the excerpt from.
$count(int) (required)
Maximum number of characters to take.
$more(string)
What to append if $str needs to be trimmed.
Default: empty string

Changelog

Since 2.5.0 Introduced.

wp_html_excerpt() code WP 6.4.3

function wp_html_excerpt( $str, $count, $more = null ) {
	if ( null === $more ) {
		$more = '';
	}

	$str     = wp_strip_all_tags( $str, true );
	$excerpt = mb_substr( $str, 0, $count );

	// Remove part of an entity at the end.
	$excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );

	if ( $str !== $excerpt ) {
		$excerpt = trim( $excerpt ) . $more;
	}

	return $excerpt;
}