Replace string with $var of the same name

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
ntbd
Forum Newbie
Posts: 21
Joined: Wed Apr 12, 2006 6:42 am

Replace string with $var of the same name

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
ntbd
Forum Newbie
Posts: 21
Joined: Wed Apr 12, 2006 6:42 am

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

no.
ntbd
Forum Newbie
Posts: 21
Joined: Wed Apr 12, 2006 6:42 am

Post by ntbd »

Thanks. Why? What did I see before that worked fine?!
Post Reply