Page 1 of 1

Replace string with $var of the same name

Posted: Wed Apr 12, 2006 6:55 am
by ntbd
Hiya, my first post here!

Building a very simple CMS and want a way for the layout pages to insert whatever bits of the content they require.

For example [_title] inserts the title, [_lastmod] the date the page was last modified, etc. All these are fetched from mysql as an array at the moment and are sorted using str_replace, but hardcoding every field of data is a bit tedius.

I would like to use the following to change any [_varname] to whatever is stored in $varname.

preg_replace("/\[_(\w*)\]/", "\$$1", $layout[0]);

\$$1 simply prints '$varname' obviously, not quite what im looking for!



many thanks.

Posted: Wed Apr 12, 2006 8:25 am
by feyd
PHP will not evaluate the replacement string as PHP code. Although there is the e modifier for patterns to do an evaluation, I cannot recommend there use as it is a security hole. Instead, I'd suggest using preg_replace_callback() to handle it.

Posted: Wed Apr 12, 2006 10:40 am
by ntbd
I've seen it done and did get it to work but have since lost it!

To avoid a security hole I could use $sql_data['title'] instead?

Posted: Wed Apr 12, 2006 11:22 am
by feyd
no.

Posted: Wed Apr 12, 2006 12:15 pm
by ntbd
Thanks. Why? What did I see before that worked fine?!