NYCPHP Meetup

NYPHP.org

[nycphp-talk] Eval a string

justin justin at justinhileman.info
Sun Mar 29 00:20:33 EDT 2009


2009/3/28 Michele Waldman <mmwaldman at nyc.rr.com>:
> I have a database string that looks like “$variable word”.
>
> When I assign it to a string the $variable is not being replaced by the
> actual value of $variable.
>
> Does anyone know how to force a replacement of a variable name with it’s
> value in a string?


Evaling anything makes a bit uncomfortable, but most especially
strings pulled out of the database. I typically use something like
this instead:

// db string is '%variable% word'
$db_string = str_replace('%variable%', $variable, $db_string);


If you have lots of things to replace, strtr() works well:

$vars = array(
  '%foo%' => $foo,
  '%bar%' => $baz,
  '%baz%' => $baz
);
$db_string = strtr($db_string, $vars);

-- 
justin
http://justinhileman.com



More information about the talk mailing list