tags:

views:

41

answers:

2

Hi,

I can't quite figure it out, I'm looking for some regex that will add an atttribute to a html tag.

For example lets say I have a string with an <a> in it, and that <a> needs an attribute added to it, so <a> get's added style="xxxx:yyyy;" . How would you go about doing this?

Ideally it would add any attribute to any tag.

Am I asking to much of php + regex, should I be building a class to do this sort of thing instead?

Cheers!

+5  A: 

It's been said a million times. Don't use regex's for HTML parsing.

    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $x = new DOMXPath($dom);

    foreach($x->query("//a") as $node)
    {   
        $node->setAttribute("style","xxxx");
    }
    $newHtml = $dom->saveHtml()
Byron Whitlock
A: 

Here is using regex:

  $result = preg_replace('/(<a\b[^><]*)>/i', '$1 style="xxxx:yyyy;">', $str);

but Regex cannot parse malformed HTML documents.

Vantomex
Why do you need the `<` in `[^><]`?
ring0
To prevent accident possibility, that is, the regex will not process `a` tags which doesn't properly closed, for example: `<a href="xxx" <p>yyy</p>`; in this case, if I didn't include the `<`, the regex will consider the scope of `a` tag is `<a href="xxx" <p>`.
Vantomex
...or if someone decides to include `<` as a literal character inside an attribute. Better fail the match then instead of messing up the HTML even further.
Tim Pietzcker