Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sprintf fail gracefully?

Tags:

php

I had to make a GUI which would allow my client 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.

like image 583
Lea Hayes Avatar asked Feb 23 '23 12:02

Lea Hayes


1 Answers

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);
like image 66
KingCrunch Avatar answered Feb 26 '23 00:02

KingCrunch