A-A+

php批量替换html标签的实例代码

2020年07月11日 我爱编程 暂无评论

这篇文章主要是对php批量替换html标签的实例代码进行了详细的介绍,需要的朋友可以过来参考下,希望对大家有所帮助。

1.把html元素全部去掉,或者保留某几个html标签,代码如下:

  1. <?php
  2. $text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
  3. echo strip_tags($text);
  4. echo "/n";
  5. // Allow <p> and <a>
  6. echo strip_tags($text'<p><a>');
  7. ?>

结果为(去掉了注释):

  1. <blockquote>Test paragraph. Other text
  2. <p>Test paragraph.</p> <a href="#fragment">Other text</a></blockquote>

2.相反,只去掉某一个html标签,代码如下:

  1. <?php
  2. function strip_only($str, $tags, $stripContent = false) {
  3.     $content = '';
  4.     if(!is_array($tags)) {
  5.         $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
  6.         if(end($tags) == '') array_pop($tags);
  7.     }
  8.     foreach($tags as $tag) {
  9.         if ($stripContent)
  10.              $content = '(.+</'.$tag.'[^>]*>|)';
  11.          $str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
  12.     }
  13.     return $str;
  14. }
  15. $str = '<font color="red">red</font> text';
  16. $tags = 'font';
  17. $a = strip_only($str, $tags); // red text
  18. $b = strip_only($str, $tags, true); // text
  19. ?>

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录