将文本修剪为一定数量的单词。

原型

wp_trim_words( string $text, int $num_words = 55, string $more = null )

描述

此功能已本地化。对于按单个字符(例如东亚语言)计算“单词”的语言,$ num_words参数将应用于单个字符的数量。

参数

$text (string) (Required) 要修剪的文字。

$num_words (int) (Optional) 单词数量。

$more (string) (Optional)  如果需要修剪$ text,要附加什么。默认’…’。

返回值

(string)  修剪过的文字。

源文件

路径:wp-includes/formatting.php

<?php
...
function wp_trim_words( $text, $num_words = 55, $more = null ) {
	if ( null === $more ) {
		$more = __( '&hellip;' );
	}
	$original_text = $text;
	$text = wp_strip_all_tags( $text );
	/*
	 * translators: If your word count is based on single characters (e.g. East Asian characters),
	 * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
	 * Do not translate into your own language.
	 */
	if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf-?8$/i', get_option( 'blog_charset' ) ) ) {
		$text = trim( preg_replace( "/[nrt ]+/", ' ', $text ), ' ' );
		preg_match_all( '/./u', $text, $words_array );
		$words_array = array_slice( $words_array[0], 0, $num_words + 1 );
		$sep = '';
	} else {
		$words_array = preg_split( "/[nrt ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
		$sep = ' ';
	}
	if ( count( $words_array ) > $num_words ) {
		array_pop( $words_array );
		$text = implode( $sep, $words_array );
		$text = $text . $more;
	} else {
		$text = implode( $sep, $words_array );
	}
	/**
	 * Filters the text content after words have been trimmed.
	 *
	 * @since 3.3.0
	 *
	 * @param string $text          The trimmed text.
	 * @param int    $num_words     The number of words to trim the text to. Default 55.
	 * @param string $more          An optional string to append to the end of the trimmed text, e.g. &hellip;.
	 * @param string $original_text The text before it was trimmed.
	 */
	return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/wp_trim_words/