网站首页 > 知识剖析 正文
PHP默认的函数有移除指定html标签,名称为strip_tags,在某些场合非常有用。
strip_tags
(PHP 3 >= 3.0.8, PHP 4, PHP 5)
strip_tags — Strip HTML and PHP tags from a string
string strip_tags ( string str [, string allowable_tags] )
弊端 :
这个函数只能保留想要的html标签,就是参数string allowable_tags。
这个函数的参数allowable_tags的其他的用法。
strip_tags($source, ”); 去掉所以的html标签。
strip_tags($source, ‘<div><img><em>’); 保留字符串中的div、img、em标签。
如果想去掉的html的指定标签。那么这个函数就不能满足需求了。于是乎我用到了这个函数。
/**
* Removes specific tags.
*/
function strip_only_tags($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.'(-->|\s[^>]*>)|)';
}
$str = preg_replace('#<!--?'.$tag.'(-->|\s[^>]*>)'.$content.'#is', '', $str);
}
return $str;
}
参数说明
$str — 是指需要过滤的一段字符串,比如div、p、em、img等html标签。
$tags — 是指想要移除指定的html标签,比如a、img、p等。
$stripContent = FALSE — 移除标签内的内容,比如将整个链接删除等,默认为False,即不删除标签内的内容。
使用说明
$target = strip_only_tags($source, array(‘a’,'em’,'b’));
移除$source字符串内的a、em、b标签。
$source='<div><a href="http://www.tsingyaun.cn" target="_blank"><img src="http://www.tsingyuan.cn/logo.png" border="0" alt="Welcome to linzl." />This a example from<em>lixiphp</em></a><strong>!</strong></div>
';
$target = strip_only_tags($source, array('a','em'));
//target results
//<div><img src="http://blog.lixiphp.com/logo.png" border="0" alt="Welcome to lixiphp." />This a example from<strong>!</strong></div>
:left;"
- 上一篇: 数据结构与算法之PHP实现队列、栈
- 下一篇: 帮您总结了面试中常用的PHP函数,您不进来看看吗?
猜你喜欢
- 2024-11-14 vue uniapp中数组的操作方法 uniapp vuecli
- 2024-11-14 JavaScript Array 对象 javascript array splice
- 2024-11-14 js中数组方法全解 js数组常用的方法
- 2024-11-14 TS类型体操,看懂你就能玩转TS了 tststs
- 2024-11-14 JS原生对数组操作的常用方法 原生js操作dom
- 2024-11-14 PHP8中获取并删除数组中最后一个元素-PHP8知识详解
- 2024-11-14 mysqli_fetch_assoc常用的函数汇总
- 2024-11-14 碎片时间学编程「203]:根据功能对数组元素进行分组
- 2024-11-14 PHP是如何实现多线程编程的? php是如何实现多线程编程的
- 2024-11-14 PHP8的数组-PHP8知识详解 php8的jit
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)