2009-07-29 112 views
6

我正在嘗試製作簡單的自定義標籤以允許在我的應用上使用自定義模板。但我無法弄清楚如何解析和替換標籤。使用PHP解析自定義標籤

(實施例)

<div class="blog"> 
<module display="posts" limit="10" show="excerpt" /> 
</div> 
<div class="sidebar"> 
<module display="users" limit="5" /> 
<module display="comment" limit="10" /> 
</div> 

每個發現模塊標籤,我想運行與參數(在標籤中作爲屬性中列出)的模塊創建功能。並將模塊標籤替換爲從該函數返回的實際HTML塊。

回答

9

您可以使用正則表達式來匹配您的自定義標籤。

$html // Your html 

preg_match_all('/<module\s*([^>]*)\s*\/?>/', $html, $customTags, PREG_SET_ORDER); 

foreach ($customTags as $customTag) { 
$originalTag=$customTag[0]; 
$rawAttributes=$customTag[1]; 

preg_match_all('/([^=\s]+)="([^"]+)"/', $rawAttributes, $attributes, PREG_SET_ORDER); 

$formatedAttributes=array(); 

foreach ($attributes as $attribute) { 
    $name=$attribute[1]; 
    $value=$attribute[2]; 

    $formatedAttributes[$name]=$value; 
} 

$html=str_replace($originalTag, yourFunction($formatedAttributes), $html); 
} 

如果你想利用一個XML的形式給出,與我聯繫,我會告訴你怎麼做。

+3

認真嗎?爲什麼使用正則表達式時,它比內置的XML函數慢得多。 – icco 2009-07-29 23:05:05

3

http://us3.php.net/manual/en/function.preg-replace-callback.php

我的合作伙伴做了工作,標籤解析...這取決於你希望實現的複雜性,你可能會喜歡用正則表達式。使用正則表達式來查找標籤,然後您可以使用您自己的首選項的字符串操作函數進一步分割字符串。 preg_replace_callback上的回調函數將允許您將標記替換爲您希望表示的任何html數據。乾杯!

編輯: (<模塊+([^ =] + = 「[^」] *「/>??????) 這應該與模塊的功能...刪除空格在<和模塊之間(SO解析它是錯誤的)。在你的自定義函數中,使用如下正則表達式匹配標籤中包含的各個參數: ([^ =] +?=「[^」]?「)

3

您可以使用simplexml解析文件,並在遍歷並查找元素後檢索屬性。這裏是一個example.

+0

如果你編寫代碼來解釋如何做到這一點,那麼這個答案可能已被接受。 – icco 2009-07-29 23:07:19

2

由於Natso建議preg_replace_callback是偉大的這種類型的解決方案。

另一種選擇是以XML格式讀取模板/文件,如果您期望驗證xml標記,則使用XmlReader並在相應節點上執行操作。作爲進一步的建議,您可能希望將Xml Namespaces用於自定義標籤,因爲這可以確保您不會發生碰撞。