使用PHP解析自定义标记

g00*_*0ne 6 php xml parsing

我正在尝试制作简单的自定义标记,以允许我的应用上的自定义模板.但我无法弄清楚如何解析和替换标签.

(例)

<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>
Run Code Online (Sandbox Code Playgroud)

对于每个找到的模块标签,我想运行带有参数的模块创建功能(在标签中列为属性).并使用从函数返回的实际HTML块替换模块标记.

Cri*_*oma 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);
}
Run Code Online (Sandbox Code Playgroud)

如果你想采用XML方法,请联系我,我会告诉你如何做到这一点.

  • 真的吗?为什么使用正则表达式比内置的XML函数慢得多. (3认同)
  • 它真的不慢. (2认同)