replacing variables in output in php
Right now I have this code.
<?php
error_reporting(E_ALL);
require_once('content_config.php');
function callback($buffer)
{
// replace all the apples with oranges
foreach ($config as $key => $value)
{
$buffer = str_replace($key, $value, $buffer);
}
return $buffer;
}
ob_start("callback");
?>
some content
<?php
ob_end_flush();
?>
in the content_config.php file:
$config['SiteName'] = 'MySiteNa开发者_如何学Pythonme';
$config['SiteAuthor'] = 'thatGuy';
What I want to do is that I want to replace the placeholders that with the key of the config array with its value.
Right now, it doesn't work :(
your callback function cant see $config. you must either pass it as an argument or declare it global
global $config;
http://php.net/manual/en/language.variables.scope.php
as an aside you can use arrays with str_replace
$buffer = str_replace(array_keys($config), array_values($config), $buffer);
this avoids a loop, which is always good.
精彩评论