Parsing Custom Tags with PHP

2019-02-10 07:38发布

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.

(example)

<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>

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.

标签: php xml parsing
5条回答
放荡不羁爱自由
2楼-- · 2019-02-10 07:56

I wrote an actual php class for this and is released under BSD. See this other thread

查看更多
干净又极端
3楼-- · 2019-02-10 07:58

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);
}

If you would like to take a XML aproach, contact me and I'll show you how to do that.

查看更多
Bombasti
4楼-- · 2019-02-10 08:03

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

My partner has done work with tag parsing... depending on the complexity you wish to achieve, you may like to use regex. Use regex to find tags, and then you can split the strings up further with string manipulation functions of your own preference. The callback feature on preg_replace_callback will let you replace the tag with whatever html data you want it to represent. Cheers!

edit: ( < module +?([^=]+?="[^"]*?" ?)? ?/>) This should match module functions... remove the space between the < and module (SO is parsing it wrong). In your custom function, match the individual parameters contained within the tag, using a regex like: ([^=]+?="[^"]?")

查看更多
放我归山
5楼-- · 2019-02-10 08:03

You can parse your file using simplexml and retrieve the attributes after iterating through and finding your elements. Here is an example.

查看更多
\"骚年 ilove
6楼-- · 2019-02-10 08:08

As Natso suggested preg_replace_callback is great for this type of solution.

Another option would be to read the template/file in as XML, if you are expecting validating xml markup, with the XmlReader and act on the appropriate nodes. As a further suggestion, you may want to use Xml Namespaces for your custom tags as this will ensure that you don't have collisions.

查看更多
登录 后发表回答