Forum Moderators: coopster

Message Too Old, No Replies

Replace variables in a string

         

YorkshireSteve

3:52 pm on Apr 18, 2004 (gmt 0)

10+ Year Member



Hi,

Several years ago I came accross a Perl regular expression which found all variables in a string and replaced it with the correct value.

I have $message stored in a database, and within $message is the text $name. My PHP code pulls a list of $name's from my database and needs to replace $name in $message. There are other variables to replace too, so the code needs to be a generic approach.

I remember that the code searched for a '$' then [a-zA-Z0-9_]. It then replaced what it found with the contents of ${variable}.

Does anyone have a similar solution available, as I aren't too good with regular expressions!

Thanks,

Steve.

YorkshireSteve

5:35 pm on Apr 18, 2004 (gmt 0)

10+ Year Member



The Perl regex I mentioned is something like this:

s/\$([A-za-z]\w*)/${$1}/g

gaouzief

5:49 pm on Apr 18, 2004 (gmt 0)

10+ Year Member



if i understood your message correctly,

eval($string) should do the job

check out:

[php.net...]

YorkshireSteve

10:13 am on Apr 19, 2004 (gmt 0)

10+ Year Member



Hi,

I've tried using eval(), but then

$message
would need to contain echo statements and such. However, if I wrap the
$message
using the correct 'here document' syntax ([uk.php.net ]) then it works:

$message = "echo <<<END\n" . $message . "\nEND;\n";
$message = eval($message]);

This is a more long-winded way to do this, but it will work for now. If I do figure out how to do it with a regex I'll post that here too.

Steve.