如何在php中使用正则表达式删除链接?
我想删除如何在php中使用正则表达式删除链接?,php,regex,Php,Regex,我想删除href属性中与此域vnexpress.net匹配的所有链接。 这是一个链接示例: <a href="http://vnexpress.net/whatever">whatever</a> 这是我的代码: $contents = preg_replace('/<a\s*href=\"*vnexpress*\"\s(.*)>(.*)<\/a>/', '', $data->content); $contents=preg_repl
href
属性中与此域vnexpress.net
匹配的所有链接。
这是一个链接示例:
<a href="http://vnexpress.net/whatever">whatever</a>
这是我的代码:
$contents = preg_replace('/<a\s*href=\"*vnexpress*\"\s(.*)>(.*)<\/a>/', '', $data->content);
$contents=preg_replace(“/(.*)/”,“$data->content);
请帮帮我!非常感谢你 您要求在此处使用正则表达式,但它不适合解析HTML
$doc = new DOMDocument;
$doc->loadHTML($html); // load the html
$xpath = new DOMXPath($doc);
$links = $xpath->query("//a[contains(@href, 'vnexpress.net')]");
foreach ($links as $link) {
$link->parentNode->removeChild($link);
}
echo $doc->saveHTML();
试试这个:
$re = "/<a[^>]+href=\"[^\"]*vnexpress.net[^>]+>(.*)<\\/a>/m";
$str = "<a id=\"\" href=\"http://vnexpress.net/whatever\">whatever <b>sss</b> </a>\n<a id=\"\" href=\"http://new.net/whatever\">whatever</a>\n";
$subst = "$1";
$result = preg_replace($re, $subst, $str);
$re=“/\n\n”;
$subst=“$1”;
$result=preg_replace($re,$subst,$str);
到目前为止,你有什么正则表达式,它给出了什么错误?
href=“\K[^”]*\bvnexpress\.net[^”]*
@AvinashRaj我试图使用你的代码,但它不起作用。试试这个”~([^]*)~'
@AvinashRaj它仍然不起作用。链接仍然存在。@Duy Nguyen如果这个答案适合你的情况,那么你可以接受这个答案。.这种模式在这种情况下会失败:
@casimirithippolyte你能改进它吗?你能解释更多(.*)吗,请。我是regex新手,所以我不明白它的意思。@casimirithippolyte是的,它将是/]+href=\“[^\”]*vnexpress.net[^>]+>(.*)/m
。非常感谢。。