Reputation: 3947
How to remove all attributes from <a>
tag except href="/index.php..."
? and add a custom class to it ?
So this:
<a href="/index.php?option=com_virtuemart&view=cart&Itemid=105&lang=en" style="float:right;">content</a>
Becomes:
<a href="index.php?option=com_virtuemart&view=cart&Itemid=105&lang=en" class="custom">content</a>
i cant manage the preg_replace to work it: `
<?php
$text = '<a href="index.php?option=com_virtuemart&view=cart&Itemid=105&lang=en" class="custom">content</a>';
echo preg_replace("/<a([a-z][a-z0-9]*)(?:[^>]*(\shref=['\"][^'\"]['\"]))?>/i", '<$1$2$3>', $text);
?>
Upvotes: 1
Views: 1111
Reputation: 13641
DOMDocument
is better, but with regex
preg_replace("/<a [^>]*?(href=[^ >]+)[^>]*>/i", '<a $1 class="custom">', $text);
Assumes no space in href
and no >
in attributes.
Upvotes: 2
Reputation: 12675
You could use DomDocument
:
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML('<a href="/index.php?option=com_virtuemart&view=cart&Itemid=105&lang=en" style="float:right;">content</a>');
$items = $doc->getElementsByTagName('a');
$href = $items->item(0)->getAttribute('href');
$value = $items->item(0)->nodeValue;
libxml_clear_errors();
echo '<a href="'.$href.'" class="custom">'.$value.'</a>';
Upvotes: 1