函数文档

wp_html_excerpt()

💡 云策文档标注

概述

wp_html_excerpt() 是一个用于安全地从 HTML 字符串中提取不超过指定字符数的前缀的函数。它处理 UTF-8 编码、HTML 标签和实体,确保提取过程不会破坏 HTML 结构。

关键要点

  • 函数安全提取 HTML 字符串的前 $count 个字符,实体不计为一个字符(例如 & 计为 4 个字符)。
  • 参数包括:$str(必需,源字符串)、$count(必需,最大字符数)、$more(可选,截断后追加的字符串,默认为空)。
  • 内部使用 wp_strip_all_tags() 去除所有 HTML 标签,并用 mb_substr() 进行多字节安全的子字符串提取。
  • 返回提取后的字符串,如果被截断,则追加 $more 参数指定的内容。

代码示例

$str = 'There are lots & lots of usages for this function. I know you can think of some! (lots more text here)';

echo wp_html_excerpt( $str, 50 );
// 输出: 'There are lots & lots of usages for this funct'

// 使用 $more 参数:
echo wp_html_excerpt( $str, 50, '...' );
// 输出: 'There are lots & lots of usages for this funct...'

📄 原文内容

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

Description

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.

Parameters

$strstringrequired
String to get the excerpt from.
$countintrequired
Maximum number of characters to take.
$morestringoptional
What to append if $str needs to be trimmed. Defaults to empty string.

Default:null

Return

string The excerpt.

Source

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;
}

Changelog

Version Description
2.5.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example

    $str = 'There are lots & <strong>lots</strong> of usages for this function. I know you can think of some! (lots more text here)';
    
    echo wp_html_excerpt( $str, 50 );
    // Output: 'There are lots & lots of usages for this funct'
    
    // Using the $more parameter:
    echo wp_html_excerpt( $str, 50, '...' );
    // Output: 'There are lots & lots of usages for this funct...'