Does anyone know a better implementation of sprintf in PHP? I was looking for something like the string formatting we have in python:
print "Hello %(name)s. Your %(name)s has just been created!" % { 'name' : 'world' }
# prints::: Hello world. Your world has just been created!
This is pretty handy to avoid repeating the same variables without need, such as:
sprintf("Hello %s. Your %s has just been created!", 'world', 'world');
# prints::: Hello world. Your world has just been created!
I guess is fairly easy to build this on my own, but don't wanna reinvent the wheel, if you know what I mean... but I could not find (maybe wrong search keywords) any trace of this anywhere.
If anyone can help, I appreciate.
Cheers,
You can use positional (but not named) arguments to do this, for example
printf('Hello %1$s. Your %1$s has just been created!', 'world');
A word of caution here: you must use single quotes, otherwise the dollar signs will cause PHP to try to substitute $s
with the value of this variable (which does not exist).
If you want named arguments then you will have to do this with a regular expression; for example, see How to replace placeholders with actual values?.
You can repeat the same placeholder with PHP's sprintf
(though it might not look as nice):
$str = sprintf('%1$s %1$s', 'yay');
// str: 'yay yay'
You can use n$
right after the %
in a placeholder, where n
is the argument position (so %1$s
refers to the first argument (as a string), %2$s
refers to the second, etc.). As you can see above, when you use placeholders that are positionally-bound, you can repeat them within the string without duplicating arguments when you call sprintf
.
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