Ren*_*ino 0 php string algorithm pattern-matching
我需要提取HTTP请求的虚拟主机名.由于这将针对每个请求完成,我正在寻找最快的方法来执行此操作.
以下代码和时间只是我学习的一些方法.
那么,有一些更快的方法来做到这一点?
$hostname = "alphabeta.gama.com";
$iteractions = 100000;
//While Test
$time_start = microtime(true);
for($i=0;$i < $iteractions; $i++){
$vhost = "";
while(($i < 20) && ($hostname{$i} != '.')) $vhost .= $hostname{$i++};
}
$time_end = microtime(true);
$timewhile = $time_end - $time_start;
//Regexp Test
$time_start = microtime(true);
for($i=0; $i<$iteractions; $i++){
$vhost = "";
preg_match("/([A-Za-z])*/", $hostname ,$vals);
$vhost = $vals[0];
}
$time_end = microtime(true);
$timeregex = $time_end - $time_start;
//Substring Test
$time_start = microtime(true);
for($i=0;$i<$iteractions;$i++){
$vhost = "";
$vhost = substr($hostname,0,strpos($hostname,'.'));
}
$time_end = microtime(true);
$timesubstr = $time_end - $time_start;
//Explode Test
$time_start = microtime(true);
for($i=0;$i<$iteractions;$i++){
$vhost = "";
list($vhost) = explode(".",$hostname);
}
$time_end = microtime(true);
$timeexplode = $time_end - $time_start;
//Strreplace Test. Must have the final part of the string fixed.
$time_start = microtime(true);
for($i=0;$i<$iteractions;$i++){
$vhost = "";
$vhost = str_replace(".gama.com","",$hostname);
}
$time_end = microtime(true);
$timereplace = $time_end - $time_start;
echo "While :".$timewhile."\n";
echo "Regex :".$timeregex."\n";
echo "Substr :".$timesubstr."\n";
echo "Explode :".$timeexplode."\n";
echo "Replace :".$timereplace."\n";
Run Code Online (Sandbox Code Playgroud)
结果时间:
While :0.0886390209198 Regex :1.22981309891 Substr :0.338994979858 Explode :0.450794935226 Replace :0.33411693573
你可以试试strtok()函数:
$vhost = strtok($hostname, ".")
Run Code Online (Sandbox Code Playgroud)
它比你的while循环的正确版本速度更快,而且更具有可读性.