返回介绍

wp_sprintf()

发布于 2017-09-11 12:57:22 字数 3533 浏览 817 评论 0 收藏 0

wp_sprintf( string $pattern )

WordPress implementation of PHP sprintf() with filters.


description


参数

$pattern

(string) (Required) The string which formatted args are inserted.

$args

(mixed) (Required) ,... Arguments to be formatted into the $pattern string.


返回值

(string) The formatted string.


源代码

File: wp-includes/formatting.php

function wp_sprintf( $pattern ) {
	$args = func_get_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) ) {
				$arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
				$fragment = str_replace("%{$matches[1]}$", '%', $fragment);
			} else {
				++$arg_index;
				$arg = isset($args[$arg_index]) ? $args[$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, strval($arg) );
		}

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

更新日志

Versiondescription
2.5.0Introduced.

相关函数

Uses

  • wp-includes/formatting.php: wp_sprintf
  • wp-includes/plugin.php: apply_filters()

Used By

  • wp-includes/taxonomy.php: get_the_taxonomies()

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 2You must log in to vote on the helpfulness of this note Contributed by Alex Mills (Viper007Bond)

    By default, wp_sprintf_l() is hooked into this function and adds the %l type which turns an array into a comma separated list. For example this code:

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

    Turns into this:

    Some cool numbers: 1, 5, 10, and 15

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文