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

标签 php algorithm string 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";

作为结果时间:

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

最佳答案

你可以试试 strtok() 函数:

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

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

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

相关文章:

c# - 如何将树过滤到共同的 parent

python - 在 Python 3 中写入文件时,TypeError : a bytes-like object is required, 不是 'str'

java - 从字符串数组中删除特定字符串

php - 像Web门户那样的ebay之类的API接口(interface)

php - Codeigniter 中的 HTML 格式的电子邮件

algorithm - 最适合调度算法

c# - 将 List<String> 中的所有字符串转换为单个逗号分隔字符串的最佳方法

php - 尝试在 sql 查询中回显一些内容

php - 如何在laravel中填充数据透视表?

algorithm - 解决类似的递归: T(n) = 3T(n/3) + n/3