preg_replace[转]
-
- 转
preg_replace是Perl内置的一种文字匹配模式,不过用起来一些参数会比ereg_relace复杂一些,实际的项目运用中,用ereg的人 还是不少,近日我写了一个获取HTML中的文本的函数,发现preg_replace居然比ereg_replace快了近一倍,两个函数如下:
用preg_replace
function GetHtmlText($str)
{
$str = preg_replace("/<sty(.*)\/style>|<scr(.*)\/script>|<!--(.*)-->/isU","",$str);
$alltext = "";
$start = 1;
for($i=0;$i<strlen($str);$i++){
if($start==0 && $str[$i]==">") $start = 1;
else if($start==1){
if($str[$i]=="<"){ $start = 0; $alltext .= " "; }
else if(ord($str[$i])>32) $alltext .= $str[$i];
}
}
$alltext = preg_replace("/&([^;&]*)(;|&)/"," ",$alltext);
$alltext = preg_replace("/ /"," ",$alltext);
$alltext = preg_replace("/ /"," ",$alltext);
return $alltext;
}
用ereg_replace
function GetHtmlText($str)
{
$str = eregi_replace("<sty(.*)/style>|<scr(.*)/script>|<!--(.*)-->","",$str);
$alltext = "";
$start = 1;
for($i=0;$i<strlen($str);$i++){
if($start==0 && $str[$i]==">") $start = 1;
else if($start==1){
if($str[$i]=="<"){ $start = 0; $alltext .= " "; }
else if(ord($str[$i])>32) $alltext .= $str[$i];
}
}
$alltext = ereg_replace("&([^;&]*)(;|&)"," ",$alltext);
$alltext = ereg_replace(" "," ",$alltext);
$alltext = ereg_replace(" "," ",$alltext);
return $alltext;
}
经过多次测试对比,用preg_replace的函数普遍在 0.08-0.12秒之间,用ereg_replace的函数却去到0.35-0.38秒之间,测试的网页为百度的主页,我的系统是图拉丁 1.1G的CPU,384M的内存。
如果你的程序中还有使用ereg处理较长文本的,建议马上更改过来。
-
- 上一主题: 幸福是一种感觉 下一主题: php抓取蜘蛛
- 查找相关文章:preg_replace
- 一
- 二
- 三
- 四
- 五
- 六
- 日
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
-
-
-
-
-
-
-
-
-
-
-
- Copyright ©2005 - 2007 老李的个人日志. All Rights Reserved
- 本日志程式及模版由老李(QQ:8989215)编写维护
- 粤ICP备06043306号