UTF.COM.CN

preg_replace比ereg_replace快多少?

作者︰IT柏拉圖 | 來源︰網絡 | 添加時間︰2006-06-30 17:18:16 | 人氣︰1312

preg_replace比ereg_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("/ {1,}/"," ",$alltext);
  $alltext = preg_replace("/ {1,}/"," ",$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(" {1,}"," ",$alltext);
  $alltext = ereg_replace(" {1,}"," ",$alltext);
  return $alltext;
}

經過多次測試對比,用preg_replace的函數普遍在 0.08-0.12秒之間,用ereg_replace的函數卻去到0.35-0.38秒之間,測試的網頁為百度的主頁,我的系統是圖拉丁 1.1G的CPU,384M的內存。

如果你的程序中還有使用ereg處理較長文本的,建議馬上更改過來。

責任編輯︰冬天來了
【字號︰ 】【去論壇討論】【發表評論】【打印本文】【告訴好友】【關閉窗口
網友評論(評論內容只代表網友觀點,與本站立場無關!)

姓名︰

驗證碼︰ 點擊刷新