gpt4 book ai didi

php - 有什么方法可以更快地提取字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:30:19 25 4
gpt4 key购买 nike

我需要提取 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";

作为结果时间:

While   :0.0886390209198Regex   :1.22981309891Substr  :0.338994979858Explode :0.450794935226Replace :0.33411693573

最佳答案

你可以试试 strtok() 函数:

$vhost = strtok($hostname, ".")

它比 while 循环的正确版本更快,并且可读性更高。

关于php - 有什么方法可以更快地提取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1683673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com