作者︰IT柏拉圖 | 來源︰網絡 | 添加時間︰2006-06-30 17:18:16 | 人氣︰1312
用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處理較長文本的,建議馬上更改過來。