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


当前回答

请记住,如果使用fgets()函数从文本文件中读取作为一行的字符串,则需要使用substr($string, -3, 1),以便获得实际字符,而不是CRLF(回车换行)的一部分。

我不认为提出这个问题的人需要这个,但对我来说,我在从文本文件的字符串中获取最后一个字符时遇到了麻烦,所以我相信其他人也会遇到类似的问题。

其他回答

你可以用很多方法找到最后一个字符,比如substr()和mb_substr()。

如果使用UTF-8等多字节字符编码,请使用mb_substr而不是substr

在这里我可以给你两个例子:

<?php
    echo substr("testers", -1);
    echo mb_substr("testers", -1);
?>

现场演示

我建议使用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()。$newstring = substr($string1, -1);

不同语言(包括C sharp和PHP)中的字符串也被认为是字符数组。

知道在理论上数组操作应该比字符串操作快,

$foo = "bar";


$lastChar = strlen($foo) -1;
echo $foo[$lastChar];

$firstChar = 0;
echo $foo[$firstChar];

然而,标准数组函数像

count();

对字符串无效。

从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)