replacing custom html tag in php

I have custom html tags in my apps, it looks like this: <wiki href="articletitle">Text</wiki> and want it replaced to be like this: <a href="http://myapps/page/articletitle">Text</a>. How I can do that in PHP?

Answers


Don't try to parse HTML with RegEx. Use DOM instead. Here's a good read: http://php.net/manual/en/book.dom.php


Ruel is right, DOM parsing is the correct way to approach it. As an exercise in regex, however, something like this should work:

<?php
$string = '<wiki href="articletitle">Text</wiki>';
$pattern = '/<wiki href="(.+?)">(.+?)<\/wiki>/i';
$replacement = '<a href="http://myapps/page/$1">$2</a>';
echo preg_replace($pattern, $replacement, $string);
?>

I'm trying to do something very similar. I recommend avoiding regEx like the plague. It's never as easy as it seems and those corner cases will cause nightmares.

Right now I'm leaning towards the Custom Tags library mentioned in this post. One of the best features is support for buried or nested tags like the code block below:

<ct:upper type="all">
    This text is transformed by the custom tag.<br />
    Using the default example all the characters should be made into uppercase characters.<br />
    Try changing the type attribute to 'ucwords' or 'ucfirst'.<br />
    <br />
    <ct:lower>
        <strong>ct:lower</strong><br />
        THIS IS LOWERCASE TEXT TRANSFORMED BY THE ct:lower CUSTOM TAG even though it's inside the ct:upper tag.<br />
        <BR />
    </ct:lower>
</ct:upper>

I highly recommend downloading the zip file and looking through the examples it contains.


I'm using Query Path to do this, here's a blog post with lots of code samples.

http://www.wingtiplabs.com/blog/posts/2013/03/18/domain-specific-markup-language/


Need Your Help

RGL Video with movi3ed

r ffmpeg rgl

I am trying to do an animation using the RGL package: