Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

improved sprintf for PHP

Tags:

python

php

printf

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,

like image 998
bruno.braga Avatar asked Dec 02 '22 23:12

bruno.braga


2 Answers

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?.

like image 173
Jon Avatar answered Dec 24 '22 00:12

Jon


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.

like image 30
John Flatness Avatar answered Dec 24 '22 00:12

John Flatness