函数文档

wp_sprintf()

💡 云策文档标注

概述

wp_sprintf() 是 WordPress 对 PHP sprintf() 函数的增强实现,支持通过过滤器自定义格式化行为。它用于将参数插入到模式字符串中,并允许开发者通过 Hook 修改格式化片段。

关键要点

  • wp_sprintf() 接受两个参数:$pattern(必需,格式化模式字符串)和 $args(必需,要插入的参数)。
  • 函数返回格式化后的字符串,支持类似 sprintf() 的占位符(如 %s),并添加了 WordPress 特有的功能。
  • 通过 apply_filters('wp_sprintf', $fragment, $arg) Hook,开发者可以过滤和修改格式化片段,实现自定义格式化逻辑。
  • 默认情况下,wp_sprintf_l() 被钩入此函数,添加了 %l 类型,用于将数组转换为逗号分隔列表。
  • 函数在 WordPress 2.5.0 中引入,5.3.0 版本正式化了 ...$args 参数签名。

代码示例

wp_sprintf( '%s: %l', __( 'Some cool numbers' ), array( 1, 5, 10, 15 ) );
// 输出:Some cool numbers: 1, 5, 10, and 15

📄 原文内容

WordPress’ implementation of PHP sprintf() with filters.

Parameters

$patternstringrequired
The string which formatted args are inserted.
$argsmixedrequired
Arguments to be formatted into the $pattern string.

Return

string The formatted string.

Source

function wp_sprintf( $pattern, ...$args ) {
	$len       = strlen( $pattern );
	$start     = 0;
	$result    = '';
	$arg_index = 0;

	while ( $len > $start ) {
		// Last character: append and break.
		if ( strlen( $pattern ) - 1 === $start ) {
			$result .= substr( $pattern, -1 );
			break;
		}

		// Literal %: append and continue.
		if ( '%%' === substr( $pattern, $start, 2 ) ) {
			$start  += 2;
			$result .= '%';
			continue;
		}

		// Get fragment before next %.
		$end = strpos( $pattern, '%', $start + 1 );
		if ( false === $end ) {
			$end = $len;
		}
		$fragment = substr( $pattern, $start, $end - $start );

		// Fragment has a specifier.
		if ( '%' === $pattern[ $start ] ) {
			// Find numbered arguments or take the next one in order.
			if ( preg_match( '/^%(d+)$/', $fragment, $matches ) ) {
				$index    = $matches[1] - 1; // 0-based array vs 1-based sprintf() arguments.
				$arg      = isset( $args[ $index ] ) ? $args[ $index ] : '';
				$fragment = str_replace( "%{$matches[1]}$", '%', $fragment );
			} else {
				$arg = isset( $args[ $arg_index ] ) ? $args[ $arg_index ] : '';
				++$arg_index;
			}

			/**
			 * Filters a fragment from the pattern passed to wp_sprintf().
			 *
			 * If the fragment is unchanged, then sprintf() will be run on the fragment.
			 *
			 * @since 2.5.0
			 *
			 * @param string $fragment A fragment from the pattern.
			 * @param string $arg      The argument.
			 */
			$_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );

			if ( $_fragment !== $fragment ) {
				$fragment = $_fragment;
			} else {
				$fragment = sprintf( $fragment, (string) $arg );
			}
		}

		// Append to result and move to next fragment.
		$result .= $fragment;
		$start   = $end;
	}

	return $result;
}

Hooks

apply_filters( ‘wp_sprintf’, string $fragment, string $arg )

Filters a fragment from the pattern passed to wp_sprintf() .

Changelog

Version Description
5.3.0 Formalized the existing and already documented ...$args parameter by adding it to the function signature.
2.5.0 Introduced.

User Contributed Notes