移除(如果存在)一个';类别';来自';a';PHP中的html元素
我想从PHP中的“a”html元素中删除一个“class”属性 例1:移除(如果存在)一个';类别';来自';a';PHP中的html元素,php,regex,Php,Regex,我想从PHP中的“a”html元素中删除一个“class”属性 例1: <p class="red">Link: <a href="http://www.google.com" style ="margin: 0px">google</a>.</p> 链接: 结果: <p class="red">Link: <a href="http://www.google.com" style ="margin: 0px">goog
<p class="red">Link: <a href="http://www.google.com" style ="margin: 0px">google</a>.</p>
链接:
结果:
<p class="red">Link: <a href="http://www.google.com" style ="margin: 0px">google</a>.</p>
<p class="red">Link: <a href="http://www.google.com" style="margin: 0px" >google</a>.</p>
链接:
例2:
<p class="red">Link: <a href="http://www.google.com" class = "link" style="margin: 0px" >google</a>.</p>
链接:
结果:
<p class="red">Link: <a href="http://www.google.com" style ="margin: 0px">google</a>.</p>
<p class="red">Link: <a href="http://www.google.com" style="margin: 0px" >google</a>.</p>
链接:
试试这个
(<a(?:\s+\w+\s*=\s*(?P<quote>["']).*?(?P=quote))*)\s+class\s*=\s*(?P<q>["']).*?(?P=q)
(正则表达式很好。我喜欢它们,尽管它们在被误用的情况下会表现得像顽皮的女孩。所以我要用prettyDomDocument:
<?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;
你不需要php或正则表达式。你需要javascript。可能重复-@aj_r,我需要在服务器端执行,示例是php字符串。我需要使用正则表达式执行。@Amparo:是的,你应该在php中执行。不,你只是字符串还是HTML文档中的一个?