我認爲解決這個問題的最好方法是在幾個不同的步驟中做到這一點。
首先,您應該使用preg_replace_callback和/(?>{([^}]+)})(.*)?{\/\1}/sim
作爲正則表達式。這會找到頂級{tag} {/ tag}。 $匹配[2]將包含內容(不帶標籤),而$匹配1將包含標籤本身。
您應該創建一個遞歸調用的函數,以便在回調中再次調用$ matches [2],以便找到子項{tags},以防萬一。這就是你將如何穿過樹。
最後,您應該創建一個處理{%tag%}的第三個函數。我會再次使用preg_replace_callback並使用switch語句來處理標記名稱。
這應該指向正確的方向。
編輯:這是一個什麼樣上述我一個全功能的演示: \
<?php
$content = <<<END
{a}
{b}I like {%first%} {%last%} a {c}lot{/c}.{/b}
{/a}
END;
echo find_tags($content);
function find_tags($content)
{
return preg_replace_callback('/(?>{([^}]+)})(.*)?{\/\1}/sim', 'find_tags_callback', $content);
}
function find_tags_callback($matches)
{
// Find and process any children tag pairs.
$matches[2] = find_tags($matches[2]);
// Process the tags {%tag%}.
$matches[2] = preg_replace_callback('/{%([^%]+)%}/sim', 'process_tags', $matches[2]);
switch ($matches[1])
{
case 'a':
$tag = 'div';
break;
case 'b':
$tag = 'p';
break;
case 'c':
$tag = 'b';
break;
}
return '<'.$tag.'>'.$matches[2].'</'.$tag.'>';
}
function process_tags($matches)
{
switch ($matches[1])
{
case 'first':
return 'Francois';
break;
case 'last':
return 'Deschenes';
break;
}
}
//
結果字符串爲:<div><p>I like Francois Deschenes a <b>lot</b>.</p></div>
。
謝謝老兄,解決了我的問題 – Omid 2011-06-14 07:50:04
不客氣! – 2011-06-14 18:06:43