2009-07-29 109 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用于自定义标签,因为这可以确保您不会发生碰撞。