我需要得到字符串的最后一个字符。 假设我有“测试者”作为输入字符串,我希望结果是“s”。PHP中怎么做呢?


当前回答

我建议使用Gordon的解决方案,因为它比substr()性能更好:

<?php 

$string = 'abcdef';
$repetitions = 10000000;

echo "\n\n";
echo "----------------------------------\n";
echo $repetitions . " repetitions...\n";
echo "----------------------------------\n";
echo "\n\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = substr($string, -1);

echo "substr() took " . (microtime(true) - $start) . "seconds\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = $string[strlen($string)-1];

echo "array access took " . (microtime(true) - $start) . "seconds\n";

die();

输出如下所示

 ---------------------------------- 
 10000000 repetitions...
 ----------------------------------

 substr() took 2.0285921096802seconds 
 array access took 1.7474739551544seconds

其他回答

我建议使用Gordon的解决方案,因为它比substr()性能更好:

<?php 

$string = 'abcdef';
$repetitions = 10000000;

echo "\n\n";
echo "----------------------------------\n";
echo $repetitions . " repetitions...\n";
echo "----------------------------------\n";
echo "\n\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = substr($string, -1);

echo "substr() took " . (microtime(true) - $start) . "seconds\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = $string[strlen($string)-1];

echo "array access took " . (microtime(true) - $start) . "seconds\n";

die();

输出如下所示

 ---------------------------------- 
 10000000 repetitions...
 ----------------------------------

 substr() took 2.0285921096802seconds 
 array access took 1.7474739551544seconds

在PHP 7.1中你可以这样做(接受负字符串偏移量的rfc):

<?php
$silly = 'Mary had a little lamb';
echo $silly[-20];
echo $silly{-6};
echo $silly[-3];
echo $silly[-15];
echo $silly[-13];
echo $silly[-1];
echo $silly[-4];
echo $silly{-10};
echo $silly[-4];
echo $silly[-8];
echo $silly{3}; // <-- this will be deprecated in PHP 7.4
die();

我让你猜一下输出。

同时,我在xenonite的性能代码中添加了以下结果:

Substr()耗时7.0334868431091秒 数组访问花费了2.3111131191254秒 直接字符串访问(负字符串偏移量)花费了1.7971360683441秒

第二个参数使用带负数的substr()。$newstring = substr($string1, -1);

从PHP 8开始,你可以使用str_ends_with()

$string = 'testers';
if (\str_ends_with($string, 's') {
    // yes
}
substr($string, -1)