0

I would like to remove a 'class' attribute from 'a' html element in PHP.

Example 1:

<p class="red">Link: <a href="http://www.google.com" style ="margin: 0px">google</a>.</p>

Result:

<p class="red">Link: <a href="http://www.google.com" style ="margin: 0px">google</a>.</p>

Example 2:

<p class="red">Link: <a href="http://www.google.com" class =  "link" style="margin: 0px"  >google</a>.</p>

Result:

<p class="red">Link: <a href="http://www.google.com" style="margin: 0px"  >google</a>.</p>
Amparo
  • 784
  • 1
  • 4
  • 21

2 Answers2

1

Regular Expressions are nice. I love them, though they'll act like naughty girls in the case of being misused. So I'm going to do it with pretty DomDocument:

<?php
    $html = <<< EOT
    <p class="red">Link: <a href="http://www.google.com" class =  "link" style="margin: 0px"  >google</a>.</p>
EOT;
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $a = $dom->getElementsByTagName('a');
    foreach($a as $tag)
      $tag->removeAttribute('class');
    $html = $dom->saveHTML();
    echo $html;
revo
  • 47,783
  • 14
  • 74
  • 117
0

Try this

(<a(?:\s+\w+\s*=\s*(?P<quote>["']).*?(?P=quote))*)\s+class\s*=\s*(?P<q>["']).*?(?P=q)

replace with \1.

See demo.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149