Reputation: 45737
Here is the scenario.
I have text in the DB that looks like this:
blah blah blah blah blah {$name} {$index}
As you may see it contains two Smarty variables {$name}
and {$index}
Now I need to assign the values to the variables with Smarty. For those who do not know Smarty, values can be easily assigned this way:
$smarty->assign('name_of_the_variable', $variable);
The problem is that this text is coming from the DB, and I do not know which variables will be in the text, so I am trying to abstract the code doing the following:
function getPageContent($page) {
$smarty = new Smarty(); // initializing Smarty
//selecting the content and saving it into the $content variable
$q='SELECT * FROM pages_blocks WHERE Page="'.$page.'"';
$r=mysql_query($q) or die(mysql_error());
while($row = mysql_fetch_array($r)) {
$content = $row['Content'];
}
//defining variables
$name = "NAME";
$index = "INDEX";
//getting all the variables inside brackets {}
preg_match_all('/{(.+)}/U', $content, $matches);
//abstracting the code assigning values to the variables found
foreach ($matches[1] as $match) {
$foo = str_replace('$', '', $match); //removing the $ to give a name to smarty
$smarty->assign(''.$foo.'', $match); //final assignation of name and its variable
}
$smarty->display('string:'.$content); //displaying the final content
}
The problem is that the final content looks like:
blah blah blah blah blah $name $index
Instead of
blah blah blah blah blah NAME INDEX
Something is wrong. Smarty is printing the variables as they are instead of running them before as normal.
Please help me.
Upvotes: 1
Views: 565
Reputation: 53319
Replace this:
$smarty->assign(''.$foo.'', $match);
With this:
$smarty->assign(''.$foo.'', ${$foo});
Upvotes: 3
Reputation: 20997
You're using regexp {(.+)}
, .+
will "eat" everything it sees, so it'll match: $name} {$index
.
You should use greedy killer: ''/\\{(.+?)\\}/U''
Upvotes: 0