我开发了一个模板系统,用于搜索{tag}等标签,并在加载时用模板文件中的内容动态替换它们。
我想要做的就是制作一个像{download='text for button'}
以下是我的所有代码的开始
//Download button
$download = '<a class="button">Download</a>';
$search = "{download}";
if (contains($string,$search))
$string=str_ireplace($search,$download,$string);
因此,当{download}返回<a class="button">Download</a>
时,{download =&#39;按钮文字&#39;}应该返回<a class="button">button text</a>
答案 0 :(得分:1)
也许这个?
<?php
$str = '{download} button {download="hello"} {download=\'hey\'} assa {download="asa"}';
$str = str_replace('{download}', '{download="Download"}', $str);
$str = preg_replace(
'/\{download(\=\"(.*)\"|\=\'(.*)\'|)\}/siU',
'<a href="#" class="button">$2</a>',
$str);
echo $str;
?>
答案 1 :(得分:1)
preg_match_all("/{download='(.*?)'}/", $string, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
$string = str_replace("{download='" . $val[1] . "'}", "<a class=\"button\">" . $val[1] . "</a>", $string);
}
这应该有用。
答案 2 :(得分:1)
<?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;
?>