preg_replace 就是用来替换字符了但是有时你会发现一些html代码使用preg_replace 函数替换不掉了,下面我们一起来看一个例子吧,具体如下所示。
例子,评论表情使用的标签<emt>1</emt>至<emt>60</emt>。
对应的图片路径/Public/images/face/1.gif至/Public/images/face/60.gif。
实现方法是使用preg_replace函数完成评论表情的显示。
- <?php
- $message='文章写的太好了<emt>3</emt><emt>34</emt>';
- $message=preg_replace('#<emt>(/d{1,2})</emt>#', '<img src="/Public/images/face/${1}.gif" />', $message);
- echo $message; //Vevb.com
- ?>
例子:
1.把html元素全部去掉,或者保留某几个html标签
- <?php
- $text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
- echo strip_tags($text);
- echo "/n";
- // Allow <p> and <a>
- echo strip_tags($text, '<p><a>');
- ?>
结果为(去掉了注释):
- <blockquote>Test paragraph. Other text
- <p>Test paragraph.</p> <a href="#fragment">Other text</a></blockquote>2.相反,只去掉某一个html标签
- <?php
- function strip_only($str, $tags, $stripContent = false) {
- $content = '';
- if(!is_array($tags)) {
- $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
- if(end($tags) == '') array_pop($tags);
- }
- foreach($tags as $tag) {
- if ($stripContent)
- $content = '(.+</'.$tag.'[^>]*>|)';
- $str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
- }
- return $str;
- }
- $str = '<font color="red">red</font> text';
- $tags = 'font';
- $a = strip_only($str, $tags); // red text
- $b = strip_only($str, $tags, true); // text
- ?>
新闻热点
疑难解答