嗯,这一个 - 为ex3v说 - 似乎是对我来说就像“重新发明轮子”的问题有点过,但我还挺喜欢它,所以我周围玩一点点,但没有正则表达式,因为我希望它是一个更通用的解决方案,它启用了自定义属性(但没有空格作为属性值)。所以它结束了这样的:
<?php
function use_template($search,$replace,$string, $options=array()) {
$searchdata = explode(" ", $search); //{download, text='Fancy'}
$template = substr($searchdata[0],1); // download
for ($i = 1; $i < sizeof($searchdata);$i++) {
$attribute = explode("=", $searchdata[$i]); //$attribute[0] = "text"; $attribute[1] = "'Fancy'}"
if (endsWith($attribute[1],'}')) {
$options[$attribute[0]] = substr($attribute[1], 0, -1);
} else {
$options[$attribute[0]] = $attribute[1];
}
}
$a = str_ireplace("{".$template."}",$replace,$string); // Hello, this is my {<a class="button">[text]</a>} button
foreach($options as $to_replace => $newval) {
$a = str_ireplace("[".$to_replace."]", $newval, $a); // Hello, this is my Fancy button
}
return $a;
}
function endsWith($haystack, $needle)
{
return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}
$download = '<a class="button" style="background-color: [color];">[text]</a>';
$search = "{download text='Fancy' color=red}";
$string = "Hello, this is my {download} button!";
$options = array("text" => "Download", "color" => "#000000");
$string= use_template($search,$download,$string,$options);
echo $string;
?>
想法是伟大的,但为什么重新发明轮子? – ex3v
它很容易设置,用户可以使用html/css基本创建自己的模板,但是使用这些标签可以使某些事情变得相同。 –