wp_sprintf

WordPress implementation of PHP sprintf() with filters.

Description

(string) wp_sprintf( (string) $pattern ); 

Returns (string)

The formatted string.

Parameters (1)

0. $pattern (string)
The string which formatted args are inserted.

Usage

  1. if ( !function_exists( 'wp_sprintf' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // The string which formatted args are inserted. 
  5. $pattern = ''; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = wp_sprintf($pattern); 
  9.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/formatting.php  
  1. function wp_sprintf( $pattern ) { 
  2. $args = func_get_args(); 
  3. $len = strlen($pattern); 
  4. $start = 0; 
  5. $result = ''; 
  6. $arg_index = 0; 
  7. while ( $len > $start ) { 
  8. // Last character: append and break 
  9. if ( strlen($pattern) - 1 == $start ) { 
  10. $result .= substr($pattern, -1); 
  11. break; 
  12.  
  13. // Literal %: append and continue 
  14. if ( substr($pattern, $start, 2) == '%%' ) { 
  15. $start += 2; 
  16. $result .= '%'; 
  17. continue; 
  18.  
  19. // Get fragment before next % 
  20. $end = strpos($pattern, '%', $start + 1); 
  21. if ( false === $end ) 
  22. $end = $len; 
  23. $fragment = substr($pattern, $start, $end - $start); 
  24.  
  25. // Fragment has a specifier 
  26. if ( $pattern[$start] == '%' ) { 
  27. // Find numbered arguments or take the next one in order 
  28. if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) { 
  29. $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : ''; 
  30. $fragment = str_replace("%{$matches[1]}$", '%', $fragment); 
  31. } else { 
  32. ++$arg_index; 
  33. $arg = isset($args[$arg_index]) ? $args[$arg_index] : ''; 
  34.  
  35. /** 
  36. * Filters a fragment from the pattern passed to wp_sprintf(). 
  37. * If the fragment is unchanged, then sprintf() will be run on the fragment. 
  38. * @since 2.5.0 
  39. * @param string $fragment A fragment from the pattern. 
  40. * @param string $arg The argument. 
  41. */ 
  42. $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg ); 
  43. if ( $_fragment != $fragment ) 
  44. $fragment = $_fragment; 
  45. else 
  46. $fragment = sprintf($fragment, strval($arg) ); 
  47.  
  48. // Append to result and move to next fragment 
  49. $result .= $fragment; 
  50. $start = $end; 
  51. return $result;