如果我有一组两个单词(用空格分隔),例如:
$str='nice couple';
Run Code Online (Sandbox Code Playgroud)
从每个单词中获取第一个字母的最快(对于服务器处理)方法是什么?IE。最终结果应该是:
数控
我知道我可以使用 $str[0] 并且获得第一个字符 ('n) 将是最快的,但是如何以如此快的方式获得第二个 ('c') 以便我进入最终 ' nc'?
首先得到用空格分隔的单词,然后得到第一个字符。
<?php
$str = 'nice couple';
$words = explode(' ', $str);
$result = $words[0][0]. $words[1][0];
echo $result;
Run Code Online (Sandbox Code Playgroud)
至于性能,另一种方法是使用正则表达式,但正如本线程中所讨论的:
执行简单操作的最好和最快的方法是使用标准函数。
Halcyon 响应更新
海森是对的。我做了一个测试来检查哪个解决方案更快:
<?php
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function solution1($text)
{
for($i=1; $i<1000000; $i++) {
$str = "nice couple";
$pos = strpos($str, " ");
$result = $str[0] . $str[$pos + 1];
}
}
function solution2($text)
{
for($i=1; $i<1000000; $i++) {
$str = 'nice couple';
$words = explode(' ', $str);
$result = $words[0][0]. $words[1][0];
}
}
$text = 'Administration\Controller\UserController::Save';
$time_start = microtime_float();
solution1($text);
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "Did solution1 in $time seconds.\n";
$time_start = microtime_float();
solution2($text);
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "Did solution2 in $time seconds.\n";
Run Code Online (Sandbox Code Playgroud)
对于 1000000 次迭代,我的解决方案将时间加倍:
在 0.61092305183411 秒内完成了 solution1。在 1.0136380195618 秒内完成了解决方案 2。
所以 Halcyon 提议更快:
$str = "nice couple";
$pos = strpos($str, " ");
$result = $str[0] . $str[$pos + 1];
Run Code Online (Sandbox Code Playgroud)