首页 > 开发 > PHP > 正文

php 使用 preg_replace 替换html代码的例子

2024-05-04 22:00:34
字体:大 中 小
来源:转载
供稿:网友

preg_replace 就是用来替换字符了但是有时你会发现一些html代码使用preg_replace 函数替换不掉了,下面我们一起来看一个例子吧,具体如下所示。

例子,评论表情使用的标签<emt>1</emt>至<emt>60</emt>。

对应的图片路径/Public/images/face/1.gif至/Public/images/face/60.gif。

实现方法是使用preg_replace函数完成评论表情的显示。
 

  1. <?php 
  2. $message='文章写的太好了<emt>3</emt><emt>34</emt>'; 
  3. $message=preg_replace('#<emt>(/d{1,2})</emt>#', '<img src="/Public/images/face/${1}.gif" />', $message); 
  4. echo $message; //Vevb.com 
  5. ?> 

例子:

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表