In PHP, inserting variables into a string can be done by using sprintf
. If I have two string variables $a
and $b
, they can be inserted into another string like this:
$string = sprintf("String containing %s two other strings %s", $a, $b);
Is there a function such that the string can specify the order of the variables inserted? Instead of specifying the format of the inserted variable, I would like to specify which variable to insert. For example like this:
$string = sprintn("String containing %2 two other strings %1 in opposite order", $a, $b);
This would be very useful in combination with gettext
, since translators would be able to change the order of the variables in the string. It could also allow for inserting the same variable multiple times, which can be useful.
I went for the following solution. By using strtr
instead of str_replace
it has the advantage of not recursively replacing any occurrences of %n
that may be present in the arguments.
function sprintn($format) {
$args = [];
for($i = 1; $i < func_num_args(); ++$i)
$args["%$i"] = func_get_arg($i);
return strtr($format, $args);
}
You can write a util to do it:
function sprintn($format,$args = array()){
for ($i=1; i<=count($args); i++){
$format = str_replace("%".$i, $args[i], $format);
}
return $format;
}