我需要得到字符串的最后一个字符。 假设我有“测试者”作为输入字符串,我希望结果是“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
其他回答
你可以用很多方法找到最后一个字符,比如substr()和mb_substr()。
如果使用UTF-8等多字节字符编码,请使用mb_substr而不是substr
在这里我可以给你两个例子:
<?php
echo substr("testers", -1);
echo mb_substr("testers", -1);
?>
现场演示
或通过直接字符串访问:
$string[strlen($string)-1];
注意,这不适用于多字节字符串。如果需要使用多字节字符串,可以考虑使用mb_* string系列函数。
PHP 7.1.0也支持负数值索引,例如$string[-1];
从PHP 8开始,你可以使用str_ends_with()
$string = 'testers';
if (\str_ends_with($string, 's') {
// yes
}
从PHP 7.1.0开始,也支持负字符串偏移量。 所以,如果你跟上时代,你可以像这样访问字符串的最后一个字符:
$str[-1]
DEMO
应@mickmackusa的要求,我补充了可能的应用方式:
<?php
$str='abcdef';
var_dump($str[-2]); // => string(1) "e"
$str[-3]='.';
var_dump($str); // => string(6) "abc.ef"
var_dump(isset($str[-4])); // => bool(true)
var_dump(isset($str[-10])); // => bool(false)
substr($string, -1)
推荐文章
- 使用PHP加密和解密密码的最佳方法是什么?
- 如何实现一个好的脏话过滤器?
- PHP中的三个点(…)是什么意思?
- Guzzlehttp -如何从guzzle6得到响应的正文?
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 格式化字节到千字节,兆字节,千兆字节
- 我可以将c#字符串值转换为转义字符串文字吗?
- 如何在PHP中获得变量名作为字符串?
- 在c#中解析字符串为日期时间
- 字符串中的单词大写
- 用“+”(数组联合运算符)合并两个数组如何工作?