开发者

How to make sprintf fail gracefully?

I had to make a GUI which would allow my 开发者_如何学Goclient to customise a greeting message. They understood that they would have to use %s to indicate where the user name would be presented. But when too many %s are specified sprintf fails with message Too few arguments.

Is there an option to either leave excess %s instances in the string or just replace them with an empty string?

// $greeting_template === 'Welcome to our site %s. Broken: %s'
$output = sprintf($greeting_template, $user_name);

Obviously there are other sprintf formatting templates, those should also fail gracefully.


You should make sure, that the message template is valid, instead of fixing broken ones

if (substr_count($greeting_template, '%s') > 1)
  throw new Exception('Too many placeholders');

substr_count()

Or you switch to a completely own string-template format like

$greeting_template = 'Welcome to our site {username}. Broken: {username}';
$replacements = array('{username}' => $username);
$message = str_replace(
              array_keys($replacements),
              array_values($replacements), 
              $greeting_template);


Maybe use str_replace instead?

$output = str_replace('%s', $user_name, $greeting_template);


Use the following format:

$greeting_template === 'Welcome to our site %1$s. Broken: %1$s';


You can make your own version of sprintf.

function sprintf2(){ // untested
 $args=func_get_args();
 $template=array_shift($args);
 return str_replace( '%s', $args, $template );
}

use it like:

sprintf2('your template %s. Other %s untouched','User123');


You don't, you validate their input to make sure that they've submitted a valid string

if(substr_count($greeting_template, '%s') > 1) { //handle error }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜