wp_sprintf( string $pattern )

WordPress implementation of PHP sprintf() with filters.


Description Description


Parameters Parameters

$pattern

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

$args

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


Top ↑

Return Return

(string) The formatted string.


Top ↑

Source Source

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

Top ↑

Changelog Changelog

Changelog
Version Description
2.5.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Alex Mills

    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

You must log in before being able to contribute a note or feedback.