Home  >  Article  >  Backend Development  >  How much faster is preg_replace than ereg_replace? _PHP Tutorial

How much faster is preg_replace than ereg_replace? _PHP Tutorial

WBOY
WBOYOriginal
2016-07-20 11:00:06858browse

preg_replace is a text matching mode built into Perl, but some parameters are more complicated to use than ereg_relace. In actual project applications, there are still many people using ereg. Recently, I wrote a method to obtain text in HTML. function, and found that preg_replace is actually nearly twice as fast as ereg_replace. The two functions are as follows:

Use preg_replace

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

Use ereg_replace

function GetHtmlText($str)
{
$str = eregi_replace("||","",$str);
$alltext = "";
$start = 1;
for($i=0;$iif($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;
}

After many tests and comparisons, the function using preg_replace is generally between 0.08-0.12 seconds, but the function using ereg_replace is between 0.35-0.38 seconds. The test webpage is Baidu’s homepage, and my system is Tualatin 1.1G. CPU, 384M memory.

If your program still uses ereg to process longer text, it is recommended to change it immediately.
($str);$i>
(.*)>
(.*)>
($str);$i>
(.*)>
(.*)>


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445549.htmlTechArticlepreg_replace is a text matching mode built into Perl, but some parameters are more complicated to use than ereg_relace. The actual In project applications, there are still many people using ereg. Recently I wrote...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn