在PHP中使用正则表达式删除标记属性

时间:2013-03-03 18:53:13

标签: php regex preg-replace

如何删除<a>以外的href="/index.php..."代码中的所有属性?并为其添加自定义类?

所以这个:

<a href="/index.php?option=com_virtuemart&view=cart&Itemid=105&lang=en" style="float:right;">content</a>

变为:

<a href="index.php?option=com_virtuemart&view=cart&Itemid=105&lang=en" class="custom">content</a>

我无法管理preg_replace来实现它:`

<?php
    $text = '<a href="index.php?option=com_virtuemart&view=cart&Itemid=105&lang=en" class="custom">content</a>';
    echo preg_replace("/<a([a-z][a-z0-9]*)(?:[^>]*(\shref=['\"][^'\"]['\"]))?>/i", '<$1$2$3>', $text);
?>

2 个答案:

答案 0 :(得分:2)

DOMDocument更好,但使用正则表达式

preg_replace("/<a [^>]*?(href=[^ >]+)[^>]*>/i", '<a $1 class="custom">', $text);

假设属性中href>没有空格。

答案 1 :(得分:1)

您可以使用DomDocument

libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML('<a href="/index.php?option=com_virtuemart&view=cart&Itemid=105&lang=en" style="float:right;">content</a>');
$items = $doc->getElementsByTagName('a');
$href = $items->item(0)->getAttribute('href');
$value = $items->item(0)->nodeValue;
libxml_clear_errors();
echo '<a href="'.$href.'" class="custom">'.$value.'</a>';
相关问题