Amparo
Amparo

Reputation: 824

Remove (if it exists) a 'class' attribute from 'a' html element in PHP

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>

Upvotes: 0

Views: 793

Answers (2)

revo
revo

Reputation: 48761

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;

Upvotes: 1

Aran-Fey
Aran-Fey

Reputation: 43316

Try this

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

replace with \1.

See demo.

Upvotes: 0

Related Questions