Chinaunix首页 | 论坛 | 博客
  • 博客访问: 167933
  • 博文数量: 90
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 1000
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-15 15:31
文章分类

全部博文(90)

文章存档

2011年(1)

2010年(20)

2009年(62)

2008年(7)

我的朋友

分类:

2009-07-30 09:19:55

preg_replace与ereg_replace那个效率更高
 

  编程序,总有一种感觉,去年的程,到了今年,总感觉慢了好多,应该这就是优化所在,自己的知识更深,技术也在更,所以每过一段时间,再读读您写的程序,看有没有可以优化的地,这是一个程序员应该做的行动。preg_replace()是Perl内置的一种文字匹配模式,不过用起来一些参数会比ereg_relace()复杂一些,实际的项目运用中,用ereg的人还是不,近日我写了一个获取HTML中的文本的函数,发现preg_replace()居然比ereg_replace()快了近一倍,两个函数如下:

用preg_replace() 
引用代码:function  GetHtmlText($str)
{
  $str  =  preg_replace("/||/isU","",$str);
  $alltext  =  "";
  $start  =  1;
  for($i=0;$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("/ {1,}/","  ",$alltext);
  $alltext  =  preg_replace("/  {1,}/","  ",$alltext);
  return  $alltext;
}

用ereg_replace()
引用代码:function  GetHtmlText($str)
{
  $str  =  eregi_replace("||","",$str);
  $alltext  =  "";
  $start  =  1;
  for($i=0;$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(" {1,}","  ",$alltext);
  $alltext  =  ereg_replace("  {1,}","  ",$alltext);
  return  $alltext;

 
  经过多次测试对,用preg_replace()的函数普遍在 0.08-0.12秒之间,用ereg_replace()的函数却去到0.35-0.38秒之间,测试的网页为百度的主页,我的系统是图拉丁 1.1G的CP,384M的内存。 
  如果你的程序中还有使用ereg处理较长文本的,建议马上更改过来。

阅读(1282) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~