[php代码]正则过滤换行(回车), 附带过滤html标签, 多余的空格等教程
最后更新: 2015-06-25
浏览次数:
注意, 不是要过滤或者替换换行(回车)符, 我们要过滤换行(回车), 因为要操作的内容(字符串)就没有换行(回车)符这些东西, 如:”\r\n”,”\n”, “\r”等, 所以, 要过滤字符串中的换行(回车), 以下代码是不起作用:
做采集站时, 将对方站点采集来的内容(html代码+换行等, 不是换行符)进行分析提取时有这么一个问题:
<?php //第一种写法 $content=str_replace("\n","",$content); echo $content; //第二种写法 str_replace("\r\n","",$content); echo $content; //第三种写法 $content=preg_replace("/\s/","",$content); echo $content; //第四补充代码 //php 不同系统的换行 //不同系统之间换行的实现是不一样的 //linux 与unix中用 /n //MAC 用 /r //window 为了体现与linux不同 则是 /r/n //所以在不同平台上 实现方法就不一样 //php 有三种方法来解决 //1、使用str_replace 来替换换行 $str = str_replace(array("/r/n", "/r", "/n"), "", $str); //2、使用正则替换 $str = preg_replace('//s*/', '', $str); //3、使用php定义好的变量 (建议使用) $str = str_replace(PHP_EOL, '', $str); ?> |
做采集站时, 将对方站点采集来的内容(html代码+换行等, 不是换行符)进行分析提取时有这么一个问题:
由于这些换行的存在, 无法给要提取的内容进行准确的定位.
比如, 要进行过滤的内容:
这里面就包含了很多换行, 回车, 以及空格(注意不是换行符, 回车符, 以及空格符),我们要过滤他们可以使用以下php正则表达式:
<?php $str=preg_replace("/\s+/", " ", $str); //过滤多余回车 ?> |
过滤之后, 我们的内容是这样的:
以下代码是过滤换行、空格、html标签等代码(附说明):
<?php $str=preg_replace("/\s+/", " ", $str); //过滤多余回车 $str=preg_replace("/<[ ]+/si","<",$str); //过滤<__("<"号后面带空格) $str=preg_replace("/<\!--.*?-->/si","",$str); //注释 $str=preg_replace("/<(\!.*?)>/si","",$str); //过滤DOCTYPE $str=preg_replace("/<(\/?html.*?)>/si","",$str); //过滤html标签 $str=preg_replace("/<(\/?head.*?)>/si","",$str); //过滤head标签 $str=preg_replace("/<(\/?meta.*?)>/si","",$str); //过滤meta标签 $str=preg_replace("/<(\/?body.*?)>/si","",$str); //过滤body标签 $str=preg_replace("/<(\/?link.*?)>/si","",$str); //过滤link标签 $str=preg_replace("/<(\/?form.*?)>/si","",$str); //过滤form标签 $str=preg_replace("/cookie/si","COOKIE",$str); //过滤COOKIE标签 $str=preg_replace("/<(applet.*?)>(.*?)<(\/applet.*?)>/si","",$str); //过滤applet标签 $str=preg_replace("/<(\/?applet.*?)>/si","",$str); //过滤applet标签 $str=preg_replace("/<(style.*?)>(.*?)<(\/style.*?)>/si","",$str); //过滤style标签 $str=preg_replace("/<(\/?style.*?)>/si","",$str); //过滤style标签 $str=preg_replace("/<(title.*?)>(.*?)<(\/title.*?)>/si","",$str); //过滤title标签 $str=preg_replace("/<(\/?title.*?)>/si","",$str); //过滤title标签 $str=preg_replace("/<(object.*?)>(.*?)<(\/object.*?)>/si","",$str); //过滤object标签 $str=preg_replace("/<(\/?objec.*?)>/si","",$str); //过滤object标签 $str=preg_replace("/<(noframes.*?)>(.*?)<(\/noframes.*?)>/si","",$str); //过滤noframes标签 $str=preg_replace("/<(\/?noframes.*?)>/si","",$str); //过滤noframes标签 $str=preg_replace("/<(i?frame.*?)>(.*?)<(\/i?frame.*?)>/si","",$str); //过滤frame标签 $str=preg_replace("/<(\/?i?frame.*?)>/si","",$str); //过滤frame标签 $str=preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si","",$str); //过滤script标签 $str=preg_replace("/<(\/?script.*?)>/si","",$str); //过滤script标签 $str=preg_replace("/javascript/si","Javascript",$str); //过滤script标签 $str=preg_replace("/vbscript/si","Vbscript",$str); //过滤script标签 $str=preg_replace("/on([a-z]+)\s*=/si","On\\1=",$str); //过滤script标签 $str=preg_replace("/&#/si","&#",$str); //过滤script标签,如javAsCript:alert ?> |