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


当前回答

我不能留下评论,但关于FastTrack的回答,也要记住,行尾可能只有一个字符。我建议

substr(trim($string), -1)

编辑:我下面的代码被某人编辑了,使它不做我所指示的事情。我已经恢复了我原来的代码,并修改了措辞,使它更清楚。

Trim(或rtrim)将删除所有空白,所以如果你确实需要检查空格、制表符或其他空白,首先手动替换各种行结束符:

$order = array("\r\n", "\n", "\r");
$string = str_replace($order, '', $string);
$lastchar = substr($string, -1);

其他回答

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

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

我建议使用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

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

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

Siemano,只获取所选目录下的php文件:

$dir    = '/home/zetdoa/ftp/domeny/MY_DOMAIN/projekty/project';
$files = scandir($dir, 1);


foreach($files as $file){
  $n = substr($file, -3);
  if($n == 'php'){
    echo $file.'<br />';
  }
}

或通过直接字符串访问:

$string[strlen($string)-1];

注意,这不适用于多字节字符串。如果需要使用多字节字符串,可以考虑使用mb_* string系列函数。

PHP 7.1.0也支持负数值索引,例如$string[-1];