使用html dom解析器去除href链接和标签

问题描述:

首先,我获取网页的html,然后删除通常出现在页面左侧或右侧(不在页面主体中)的href链接。 Href链接正在被删除,但其标签未被删除。使用html dom解析器去除href链接和标签

例子:

<a href='http://test.blogspot.com/2012/11/myblog.html'>London</a> 

链接已经被删除,但不是的标签,即 '伦敦'。我如何删除html源代码中的完整行?我使用下面的代码是:

$string = strip_tags($html_source_code, '<a>', TRUE); 

function strip_tags($text, $tags = '', $invert = FALSE) { 
     preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags); 
     $tags = array_unique($tags[1]); 
     if(is_array($tags) AND count($tags) > 0) { 
     if($invert == FALSE) { 
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text); 
     } 
     else { 
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text); 
     } 
     } 
     elseif($invert == FALSE) { 
     return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text); 
     } 
return $text; 
} 
+0

那么,你期望'return $ text;'返回什么? – samayo

如果我用你的代码,我得到一个致命错误:无法重新声明strip_tags()。

将名称函数更改为像my_strip_tags这样的工作正常。

function my_strip_tags($text, $tags = '', $invert = FALSE) { 
     preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags); 
     $tags = array_unique($tags[1]); 
     if(is_array($tags) AND count($tags) > 0) { 
     if($invert == FALSE) { 
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text); 
     } 
     else { 
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text); 
     } 
     } 
     elseif($invert == FALSE) { 
     return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text); 
     } 
return $text; 
} 

$html_source_code = "Beginning of content ... <a href='http://test.blogspot.com/2012/11/myblog.html'>London</a> ... end of content."; 

echo "<p>".$html_source_code."</p>"; 

$string = my_strip_tags($html_source_code, '<a>', TRUE); 

echo "<p>".$string."</p>"; 

,打印:

的内容开始...... London ...的内容结束。

内容开始......内容结束。

+0

谢谢。有用。 – Jerry3456

$link = "<a href='http://test.blogspot.com/2012/11/myblog.html'>London</a>"; 

function erraser($theLink, $checkTag){ 

    if(strpos($theLink, $checkTag) == true){ 

     for($i=0; $i< strlen($theLink); $i++){ 
     $link[$i] = ''; 
     return $link[$i]; 
     } 
     }else{ 
     return $theLink; 
    } 

} 

现在,让我们看看这个:

所有你需要做的是给erraser()函数的两个参数,然后链接的变量,任何文本通过

确认该链接如果你为例如:echo erraser($link, 'href');它会删除链接,并return什么也没有。不过,若你给它内echo erraser($link, '----');然后,会发出链接london,意义,它会检查它是否是一个链接或没有做必要的功能