Warm tip: This article is reproduced from serverfault.com, please click

xml-使用PHP解析自定义标签

(xml - Parsing Custom Tags with PHP)

发布于 2009-07-29 17:15:23

我想制作简单的自定义标签,以允许在我的应用程序上使用自定义模板。但是我不知道如何解析和替换标签。

(例子)

<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块替换module标记。

Questioner
g00se0ne
Viewed
0
Cristian Toma 2009-07-30 01:46:27

你可以使用正则表达式来匹配你的自定义标签。

$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方式,请与我联系,我将向你展示如何做到这一点。