1

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);
?>
aspirinemaga
  • 3,753
  • 10
  • 52
  • 95

2 Answers2

2

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.

MikeM
  • 13,156
  • 2
  • 34
  • 47
1

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>';
bitWorking
  • 12,485
  • 1
  • 32
  • 38