嗯,這一個 - 爲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基本創建自己的模板,但是使用這些標籤可以使某些事情變得相同。 –