Parsing custom tags using PHP

I am trying to make simple custom tags to allow custom templates in my application. But I can’t figure out how to parse and replace 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 module tag found, I want to run a module creation function with parameters (indicated as attributes in the tag). And replace the module tag with the actual HTML snippet that is returned from the function.

+6
xml php parsing
source share
5 answers

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 want to use XML aproach, contact me and I will show you how to do it.

+9
source share

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

My partner did the parsing of tags ... depending on the complexity you want to achieve, you can use regex. Use a regular expression to search for tags, and then you can split the lines further with the string manipulation functions of your choice. The callback function on preg_replace_callback will allow you to replace the tag with any html data that you want to submit. Hooray!

edit: (<module +? ([^ =] +? = "[^"] *? "?) ?? /">) This should correspond to the functions of the module ... remove the space between <and the module (SO parses it incorrectly ) In your user-defined function, match the individual parameters contained in the tag using a regular expression: ([^ =] +? = "[^"]? ")

+3
source share

You can parse your file using simplexml and get the attributes after iterating and searching for your elements. The following is an example .

+3
source share

As Natso suggested, preg_replace_callback great for this type of solution,

Another option is to read the template / file in XML format if you are expecting xml markup verification with XmlReader and act on the corresponding nodes. As an additional suggestion, you can use the Xml Namespaces for your custom tags, as this ensures that you have no collisions.

+2
source share

I wrote an actual php class for this and released under BSD. Check out this other topic.

+1
source share

All Articles