I have a custom html tag in my apps that looks like this:
<wiki href="articletitle">Text</wiki>`
and want to replace it with this:
<a href="http://myapps/page/articletitle">Text</a>
How I can do that in PHP?
I have a custom html tag in my apps that looks like this:
<wiki href="articletitle">Text</wiki>`
and want to replace it with this:
<a href="http://myapps/page/articletitle">Text</a>
How I can do that in 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.
Do not use regex when a legitimate parser can do the job more reliably.
Since your document contains invalid markup, you will need to silence the parser's discontent before the html is loaded.
I prefer to use DOMDocument and its declarative/self-explanatory methods.
Code: (Demo)
$html = <<<HTML
<div>
<wiki href="articletitle">Text</wiki>
</div>
HTML;
$appPath = 'http://myapps/page/';
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach ($dom->getElementsByTagName('wiki') as $wiki) {
$a = $dom->createElement('a');
$a->setAttribute('href', $appPath . $wiki->getAttribute('href'));
$a->nodeValue = $wiki->nodeValue;
$wiki->parentNode->replaceChild($a, $wiki);
}
echo $dom->saveHTML();
Output:
<div>
<a href="http://myapps/page/articletitle">Text</a>
</div>