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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With