作为一个站长,一般采集过来的内容难免会带有html标签,如果有太多的标签会影响之后的数据分析或提取,所以需要过滤掉,吾爱编程为你介绍一下如何去除
方法一:
$content = preg_replace("/]*>/i", "", $content);
$content = preg_replace("//i", "", $content);
$content = preg_replace("/
$content = preg_replace("//i", "", $content);
$content = preg_replace("//i", "", $content);//注释内容
$content = str_replace("\r","",$content);//过滤换行
$content = str_replace("\n","",$content);//过滤换行
$content = str_replace("\t","",$content);//过滤换行
$content = str_replace("\r\n","",$content);//过滤换行
$content = preg_replace("/\s+/", " ", $content);//过滤多余回车
$content = preg_replace("/
$content = preg_replace("//si","",$content); //过滤html注释
$content = preg_replace("//si","",$content); //过滤DOCTYPE
$content = preg_replace("//si","",$content); //过滤html标签
$content = preg_replace("//si","",$content); //过滤head标签
$content = preg_replace("//si","",$content); //过滤meta标签
$content = preg_replace("//si","",$content); //过滤body标签
$content = preg_replace("//si","",$content); //过滤link标签
$content = preg_replace("//si","",$content); //过滤form标签
$content = preg_replace("/cookie/si","COOKIE",$content); //过滤COOKIE标签
方法二:
strip_tags
strip_tags($str) 去掉 HTML 及 PHP 的标记
语法: string strip_tags(string str);
传回值: 字串
函式种类: 资料处理
内容说明 :
解析:本函式可去掉字串中包含的任何 HTML 及 PHP 的标记字串。若是字串的 HTML 及 PHP 标签原来就有错,例如少了大于的符号,则也会传回错误。这个函数和 fgetss() 有着相同的功能
例子
echo strip_tags("Hello world!"); # Hello world!
htmlspecialchars
这个函数把html中的标签转换为html实体,博客的代码展示就必须使用这个函数,要不贴出来的代码就会被执行了。
预定义的字符是:
& (和号) 成为 &
” (双引号) 成为 ”
‘ (单引号) 成为 ‘
< (小于) 成为 < > (大于) 成为 >
例子
$new = htmlspecialchars("Test", ENT_QUOTES); echo $new; # <a href='test'>Test</a> # 如果需要展现
,那么浏览器解析HTML的时候会自动将他变为换行 # 但是通过htmlspecialchars就可以让< 变为 '
与htmlspecialchars功能相反的函数是htmlspecialchars_decode,他会把HTML实体转化为字符!