从字符串中删除HTML标记和内部文本

时间:2014-04-03 07:20:34

标签: php html

我一直在使用strip_tags从字符串中删除HTML标记。但是,这种方法仍然保留了那些内部文本。

如何从字符串中删除标记和内部文本?

例如:

Hello World <a href="/world">Remove me please!</a>, hello my friends.

//expected result

Hello world, hello my friends.

1 个答案:

答案 0 :(得分:-1)

取自strip_tags()

的PHP文档的评论
<?php 
function strip_tags_content($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; 
} 
?>

归功于http://www.php.net/strip_tags#86964

相关问题