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
A word of caution here: you must use single quotes, otherwise the dollar signs will cause PHP to try to substitute
$swith 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?.