我需要获取字符串的最后一个字符.假设我有"测试者"作为输入字符串,我希望结果为"s".我怎么能用PHP做到这一点?
Ric*_*ams 930
substr("testers", -1); // returns "s"
Run Code Online (Sandbox Code Playgroud)
Gor*_*don 68
或者通过直接字符串访问:
$string[strlen($string)-1];
Run Code Online (Sandbox Code Playgroud)
请注意,这不适用于多字节字符串.如果需要使用多字节字符串,请考虑使用mb_*
字符串系列函数.
从PHP 7.1.0开始,也支持负数数字索引,例如 $string[-1];
Rya*_*erd 38
在即将发布的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();
Run Code Online (Sandbox Code Playgroud)
我会让你猜出输出.
另外,我将这个结果添加到xenonite的性能代码中:
substr()耗时7.0334868431091秒
数组访问耗时2.3111131191254秒
直接字符串访问花了1.7971360683441秒
Sla*_*ack 16
我不能留下评论,但关于FastTrack的答案,还要记住,行结尾可能只是单个字符.我会建议
substr(trim($string), -1)
Run Code Online (Sandbox Code Playgroud)
编辑: 我的代码是由某人编辑的,这使得它没有按照我的指示行事.我已恢复原始代码并更改了措辞以使其更清晰.
trim
(或rtrim
)将删除所有空格,因此如果您确实需要检查空格,制表符或其他空格,请先手动替换各种行尾:
$order = array("\r\n", "\n", "\r");
$string = str_replace($order, '', $string);
$lastchar = substr($string, -1);
Run Code Online (Sandbox Code Playgroud)
Yes*_*rry 14
从 PHP 8 开始,您现在可以使用str_ends_with()
$string = 'testers';
if (\str_ends_with($string, 's') {
// yes
}
Run Code Online (Sandbox Code Playgroud)
从PHP 7.1.0开始,还支持负字符串偏移量。因此,如果您紧跟时代发展,可以访问字符串中的最后一个字符,如下所示:
$str[-1]
Run Code Online (Sandbox Code Playgroud)
我建议去寻找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();
Run Code Online (Sandbox Code Playgroud)
输出类似的东西
----------------------------------
10000000 repetitions...
----------------------------------
substr() took 2.0285921096802seconds
array access took 1.7474739551544seconds
Run Code Online (Sandbox Code Playgroud)