Re: variable replacement in string



On 5/10/2012 8:44 AM, M. Strobel wrote:
Hi,

I am still searching a function in PHP to execute variable replacement in strings.
Other languages do have this, but for PHP I can only find sprintf() and string replace.

I have

$t = ' - solved - ';
$msg = 'The problem is $t';

I want now:

echo fxx($msg);

print out "The problem is - solved - ".

Please don't tell me about $msg = "The problem is $t"; just think of $msg like a
template read from a file.

/Str.

There's also preg_replace(), but that's a bit of overkill for something so simple.

str_replace() works fine, especially since both the search and replace parameters can be arrays. But when using message templates, I don't use variable names - it ties the template tightly to the code.

Rather, I use templates like:

$t = ' - solved - ';
$template = 'The problem is %PROB_STAT%';
echo str_replace('%PROB_STAT%', $t, $template);

Or, if you had the possibility of more than one string to substitute:

$search = array('$PROB_STAT%');
$replace = array($t);
echo str_replace('%PROB_STAT%', $t, $template);

Your method requires the template know that $t is the value in the program, and requires the program to ensure $t is defined properly in this scope. Neither is a good idea.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@xxxxxxxxxxxxx
==================
.



Relevant Pages

  • Re: variable replacement in string
    ... I am still searching a function in PHP to execute variable replacement in strings. ... but for PHP I can only find sprintfand string ... the template tightly to the code. ...
    (comp.lang.php)
  • Re: variable replacement in string
    ... I am still searching a function in PHP to execute variable replacement in strings. ... but for PHP I can only find sprintfand string ... the template tightly to the code. ... You are also now closely coupling your template to your code. ...
    (comp.lang.php)
  • Re: Object of class Person could not be converted to string
    ... PHP has been lousy at maintaining backward compatibility. ... Objects are always converted to the string "Object". ... there's no reasonable gain in usability by forcing it ...
    (comp.lang.php)
  • User Defined Types
    ... I have a global template in the startup directory. ... the information is combined into one string using the ... I would like to use the Sdr type with the SaveUserInfo code. ...
    (microsoft.public.word.vba.general)
  • Re: powerpoint automation via vb.net
    ... Dim template As String ... generate Powerpoint presentation?", "Generate Powerpoint", ... render all the ppt as it will be 60 slides. ...
    (microsoft.public.office.developer.automation)