Regex,在html (php)中向标记添加属性

时间:2021-02-04 19:35:23

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

我不太明白,我在找一些regex,它会添加一个对html标签的引用。

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?

例如,假设有一个字符串,其中有一个,而需要添加一个属性,因此 get的添加样式="xxxx: yyyyy;"。你要怎么做呢?

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?

我是否要求使用php + regex,我是否应该构建一个类来做这种事情?

Cheers!

干杯!

2 个解决方案

#1


18  

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

这已经说了一百万次了。不要将regex用于HTML解析。

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

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

#2


11  

Here is using regex:

这是使用正则表达式:

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

but Regex cannot parse malformed HTML documents.

但是Regex不能解析格式错误的HTML文档。

#1


18  

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

这已经说了一百万次了。不要将regex用于HTML解析。

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

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

#2


11  

Here is using regex:

这是使用正则表达式:

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

but Regex cannot parse malformed HTML documents.

但是Regex不能解析格式错误的HTML文档。