可能重复: 在PHP中替换字符串的最快方法
我试图管理我在html标记中创建的自定义变量,例如:
<title>{myTitle}</title>
现在如何使用PHP替换那些自定义变量“{.}”?我看到大多数的模板引擎都能做到这一点。
如有任何意见,将不胜感激:)
发布于 2011-07-27 02:00:59
这是模板引擎的非常简单的版本。显然,您需要将其放入具有更多功能的类中:)
显示页面
<?php
define(TEMPLATES_LOCATION, 'templates/');
function TemplateFunction ($template, $replaces) {
$template = file_get_contents(TEMPLATES_LOCATION . $template);
if (is_array($replaces)) {
foreach($replaces as $replacekey => $replacevalue){
$template = str_replace('{$' . $replacekey . '}', $replacevalue, $template);
}
}
return $template;
}
$keys = array(
'TITLE' => 'This is page title',
'HEADER' => 'This is some header'
);
echo TemplateFunction('body.tpl', $keys);
?>
模板文件(位于Template/body.tpl.file)
<html>
<head>
<title>{$TITLE}</title>
</head>
<body>
<h1>{$HEADER}</h1>
</body>
</html>
(编辑)单文件版本
<?php
define(TEMPLATES_LOCATION, '');
function TemplateFunction ($template, $replaces) {
// $template = file_get_contents(TEMPLATES_LOCATION . $template);
if (is_array($replaces)) {
foreach($replaces as $replacekey => $replacevalue){
$template = str_replace('{$' . $replacekey . '}', $replacevalue, $template);
}
}
return $template;
}
$keys = array(
'TITLE' => 'This is page title',
'HEADER' => 'This is some header'
);
$template = '<html>
<head>
<title>{$TITLE}</title>
</head>
<body>
<h1>{$HEADER}</h1>
</body>
</html>';
echo TemplateFunction($template, $keys);
?>
发布于 2011-07-27 01:44:55
PHP已经是一个基本的模板环境,或者您可以使用像Smarty这样的工具来获得更多的功能。但是使用PHP本身,您可以简单地包含标准变量:
<title><?= $myTitle ?></title>
发布于 2011-07-27 01:49:11
$arr = new array();
$arr["test"] = "hello";
$arr["foo"] = "world"
foreach ($arr as $key => $value) {
$yourTemplateAsString = str_replace("{".$key."}", $value, $yourTemplateAsString);
}
简单的解决办法..。当然,您可以用正则表达式做一些花哨的事情,然后添加foreach之类的东西。
https://stackoverflow.com/questions/6842225
复制相似问题