Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中使用正则表达式删除标记属性_Php_Regex_Preg Replace - Fatal编程技术网

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

在PHP中使用正则表达式删除标记属性,php,regex,preg-replace,Php,Regex,Preg Replace,如何从 变成: <a href="index.php?option=com_virtuemart&view=cart&Itemid=105&lang=en" class="custom">content</a> 我无法管理preg_替换以使其正常工作:` <?php $text = '<a href="index.php?option=com_virtuemart&view=cart&Itemid=105

如何从

变成:

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

我无法管理preg_替换以使其正常工作:`

<?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);
?>

您可以使用
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>';
libxml\u使用\u内部错误(true);
$doc=新的DOMDocument();
$doc->loadHTML(“”);
$items=$doc->getElementsByTagName('a');
$href=$items->item(0)->getAttribute('href');
$value=$items->item(0)->nodeValue;
libxml_clear_errors();
回声';

DOMDocument
更好,但使用regex

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

假设
href
中没有空格,属性中也没有

使用解析器听起来确实更容易。如果你说的是html解析器,我会尝试使用它,但我无法管理它。可能重复:是的,这就是我说的。也许你可以发布你尝试过的东西,我们可以帮助你?@Wiseguy-我尝试过:
$doc=newDOMDocument()$doc->loadHTML($data->cart\u show),但我已经看到了答案,我的代码还没有完成。谢谢你指点我,我已经试过了,但是没有libxml(我不知道),它也不起作用。
preg_replace("/<a [^>]*?(href=[^ >]+)[^>]*>/i", '<a $1 class="custom">', $text);