使用PHP解析自定义标签 [英] Parsing Custom Tags with PHP

查看:265
本文介绍了使用PHP解析自定义标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to make simple custom tags to allow custom templates on my app. But I can't figure out how to parse and replace the tags.

(示例)

<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标记.

for each found module tag, I want to run the module creation function with the parameters (listed in the tag as attributes). And replace the module tag, with an actual HTML chunk that gets returned from the function.

推荐答案

您可以使用正则表达式来匹配您的自定义标记.

You can use regular expressions to match your custom tags.

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

这篇关于使用PHP解析自定义标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆