|
Posted by Richard Lynch on 04/07/05 06:51
On Wed, April 6, 2005 4:23 am, Duncan Hill said:
> I have a snippet of code that looks something like:
> if (is_array($p_sub_values)) {
> foreach ($p_sub_values as $i => $v) {
> $p_sub_values_str[$i] = "'$v'";
> }
> $s = join(',', $p_sub_values_str);
> $r = htmlentities(sprintf($tmp[0], $s, ENT_QUOTES);
> }
>
> $tmp[0] in this case contains a string like 'Fred likes %1$s on his %2$s',
> taking advantage of positional substitution with sprintf.
>
> The function call to this snippet can have an optional array passed. My
> need/desire is to substitute each element of the array into the
> appropriate
> position with sprintf. So far I've tried:
> $r = htmlentities(sprintf($tmp[0], $s, ENT_QUOTES);
> $r = htmlentities(sprintf($tmp[0], ${$s}, ENT_QUOTES);
As far as I know, there's no super easy way to do what you want for an
arbitrary number of arguments...
While PHP does have support for functions to take an arbitrary number of
arguments, there's no way to pass those on down to something else, like $@
in shell (and Perl?). Least not as far as I know.
> and a few other bits and pieces, all to no avail (error is about not
> enough
> arguments).
>
> Is there any way to accomplish this in PHP, or do I need to roll my own
> substitution code? The array can obviously be anything from a single
> value
> to 'unlimited' (though in practice will probably be less than 5).
You could, of course, do something like:
list($a1,$a2,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$a10) = $tmp;
sprintf($a1, $a2, $a3, $a4, $a5, $a6, $a7, $a8, $a9, $a10);
Depending on your error reporting, you'll get messages, so you'll need to
use @ to suppress them.
I guess you could use count() and do string manipulation to build the
sprintf(...) you want and then use eval() and you could then avoid the
warnings...
Aha!
Wait a minute.
I *THINK* this will do what you want:
call_user_func_array('sprintf', $tmp);
Only I'm not sure you can use a built-in function for it...
http://php.net/call_user_func_array
Never used it, so not really sure it fits the bill.
--
Like Music?
http://l-i-e.com/artists.htm
[Back to original message]
|