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?
views:
91answers:
3
+1
A:
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
2010-10-04 02:06:49
A:
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);
?>
tagawa
2010-10-04 03:22:48
You should at least make the quantifiers lazy, or this will blow up.
Tim Pietzcker
2010-10-04 07:20:49
Thanks - have done.
tagawa
2010-10-27 09:56:27
A:
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.
Snekse
2010-10-15 17:22:01