由于有人提到效率,出于好奇,我已经对到目前为止给出的功能进行了基准测试:
function startsWith1($str, $char) {
return strpos($str, $char) === 0;
}
function startsWith2($str, $char) {
return stripos($str, $char) === 0;
}
function startsWith3($str, $char) {
return substr($str, 0, 1) === $char;
}
function startsWith4($str, $char){
return $str[0] === $char;
}
function startsWith5($str, $char){
return (bool) preg_match('/^' . $char . '/', $str);
}
function startsWith6($str, $char) {
if (is_null($encoding)) $encoding = mb_internal_encoding();
return mb_substr($str, 0, mb_strlen($char, $encoding), $encoding) === $char;
}
这是我每台平均运行100.000次的DualCore计算机上的结果
// Testing '_string'
startsWith1 took 0.385906934738
startsWith2 took 0.457293987274
startsWith3 took 0.412894964218
startsWith4 took 0.366240024567
startsWith5 took 0.642996072769
startsWith6 took 1.39859509468
// Tested "string"
startsWith1 took 0.384965896606
startsWith2 took 0.445554971695
startsWith3 took 0.42377281189
startsWith4 took 0.373164176941
startsWith5 took 0.630424022675
startsWith6 took 1.40699005127
// Tested 1000 char random string [a-z0-9]
startsWith1 took 0.430691003799
startsWith2 took 4.447286129
startsWith3 took 0.413349866867
startsWith4 took 0.368592977524
startsWith5 took 0.627470016479
startsWith6 took 1.40957403183
// Tested 1000 char random string [a-z0-9] with '_' prefix
startsWith1 took 0.384054899216
startsWith2 took 4.41522812843
startsWith3 took 0.408898115158
startsWith4 took 0.363884925842
startsWith5 took 0.638479948044
startsWith6 took 1.41304707527
如您所见,将干草堆作为数组来查找第一位置的char始终是最快的解决方案。 无论字符串长度如何,它始终以相等的速度运行。 当字符串不以前缀开头时,对于短字符串,使用startsWith比stripos8快,但是对于长字符串,使用速度较慢。 区别是无关紧要的。 stripos长长的琴弦非常慢。 preg_match不管字符串长度如何,其性能基本相同,但速度中等。 stripos8解决方案的性能最差,尽管可能更可靠。
假设这些数字是用于100.000次运行,那么很明显,我们正在谈论的是每次通话0.0000x秒。 除非一个应用程序正在做startsWith来检查生计,否则为了效率而选择另一个是毫无价值的。