【问题标题】:Remove HTML tags and inner text from string [duplicate]从字符串中删除 HTML 标记和内部文本 [重复]
【发布时间】:2014-04-03 07:20:33
【问题描述】:

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

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

例如:

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

//expected result

Hello world, hello my friends.

【问题讨论】:

  • 你能举个例子吗?输入和期望的输出。
  • 你考虑过DomDocument吗?请发布您要解析的 HTML 示例。
  • 还剩下什么?我想您需要使用 DOM 解析器来额外添加您真正想要的部分。
  • 我添加了一个例子。
  • $str = "他fdgdfgdfgllo"; echo preg_replace('#<.>.*?*?>#', '', $str);这就是你想要的。

标签: php html


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-19
    • 2017-09-06
    • 2012-03-28
    相关资源
    最近更新 更多