我需要得到字符串的最后一个字符。 假设我有“测试者”作为输入字符串,我希望结果是“s”。PHP中怎么做呢?
当前回答
或通过直接字符串访问:
$string[strlen($string)-1];
注意,这不适用于多字节字符串。如果需要使用多字节字符串,可以考虑使用mb_* string系列函数。
PHP 7.1.0也支持负数值索引,例如$string[-1];
其他回答
substr($string, -1)
substr("testers", -1); // returns "s"
或者,对于多字节字符串:
mb_substr("multibyte string…", -1); // returns "…"
我建议使用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
或通过直接字符串访问:
$string[strlen($string)-1];
注意,这不适用于多字节字符串。如果需要使用多字节字符串,可以考虑使用mb_* string系列函数。
PHP 7.1.0也支持负数值索引,例如$string[-1];
不同语言(包括C sharp和PHP)中的字符串也被认为是字符数组。
知道在理论上数组操作应该比字符串操作快,
$foo = "bar";
$lastChar = strlen($foo) -1;
echo $foo[$lastChar];
$firstChar = 0;
echo $foo[$firstChar];
然而,标准数组函数像
count();
对字符串无效。
推荐文章
- Printf与std::字符串?
- 不区分大小写的“in”
- 原则-如何打印出真正的sql,而不仅仅是准备好的语句?
- 如何从关联PHP数组中获得第一项?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- PHP/MySQL插入一行然后获取id
- 我如何排序一个多维数组在PHP
- 如何在PHP中截断字符串最接近于一定数量的字符?
- PHP错误:“zip扩展名和unzip命令都没有,跳过。”
- Nginx提供下载。php文件,而不是执行它们
- Json_encode()转义正斜杠
- 如何在PHP中捕获cURL错误
- Ruby数组到字符串的转换
- 为什么在Java和。net中不能修改字符串?
- 如何要求一个分叉与作曲家?