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.
Return Return
(string) The formatted string.
Source Source
File: wp-includes/formatting.php
4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 | 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 ; } |
Expand full source code Collapse full source code View on Trac
Changelog Changelog
Version | Description |
---|---|
2.5.0 | Introduced. |
User Contributed Notes User Contributed Notes
You must log in before being able to contribute a note or feedback.
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: