RE: Recursive Interpolation

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Chuck Wolber wrote:
> The method I've come up with in the meantime, I believe is much more
> effective than heredocs, but still an ugly hack:
>
> function interpolate ($text, $msg_variable) {
>     $msg_key = '_FP_VAR_';
>
>     foreach (array_keys($msg_variable) as $key) {
>         $token = $msg_key.$key;
>         $text = preg_replace("/$token/", "$msg_variable[$key]",
>     $text); }
>
>     return ($text);
> }

What's ugly about it?  I saw your earlier post I was actually planning on
responding and suggesting something exactly like you just came up with.  My
version had the $token surrounded by markers, such as

This is a ?:token:?

but that's the only difference.  I think it's fairly clean and logical.

The only problem I can see with this approach is that it's inefficient as
$msg_variable gets larger or the $text gets larger, since you're iterating
through every key of the former, even if the token isn't in $text, and you
run preg_replace() once for each token, but that shouldn't hurt you unless
you really have a heavy traffic site, IMHO.

I toyed around with using preg_replace_callback() for this eariler, but the
only problem with it is that you can't create a callback that accepts more
than just one variable (the array of matches).  This means I couldn't get
the equivalent of your $msg_variable passed to the callback, so I had to
make it global in the callback function (yuk).  If it weren't for that it'd
be a perfect solution, because preg_replace_callback would only be called
once and the function wouldn't need to iterate through all of $msg_variable.
It's times like that that I miss Perl's more powerful variable scoping
rules.  Ah well...

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux