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
  • 724
  • 1
  • 4
  • 19

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
  • 45,845
  • 14
  • 70
  • 113
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
  • 35,525
  • 9
  • 94
  • 135