php 如何在PHP中获取字符串的最后一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2681786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:20:29  来源:igfitidea点击:

How to get the last char of a string in PHP?

phpstring

提问by streetparade

I need to get the last character of a string. Say I have "testers" as input string and I want the result to be "s". how can I do that in PHP?

我需要获取字符串的最后一个字符。假设我有“testers”作为输入字符串,我希望结果是“s”。我怎样才能在 PHP 中做到这一点?

回答by Rich Adams

substr("testers", -1); // returns "s"

Or, for multibytes strings :

或者,对于多字节字符串:

substr("multibyte string…", -1); // returns "…"

回答by knittl

substr($string, -1) 

回答by Gordon

Or by direct string access:

或通过直接字符串访问

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

Note that this doesn't work for multibyte strings. If you need to work with multibyte string, consider using the mb_*string family of functions.

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

As of PHP 7.1.0 negative numeric indices are also supported, e.g just $string[-1];

从 PHP 7.1.0 开始,还支持负数索引,例如 $string[-1];

回答by RyanNerd

From PHP 7.1 you can do this (Accepted rfc for negative string offsets):

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

I'll let you guess the output.

我会让你猜输出。

Also, I added this to xenonite'sperformance code with these results:

此外,我将此添加到氙气的性能代码中,结果如下:

substr() took 7.0334868431091seconds

array access took 2.3111131191254seconds

Direct string access (negative string offsets) took 1.7971360683441seconds

substr() 耗时 7.0334868431091 秒

数组访问耗时 2.3111131191254 秒

直接字符串访问(负字符串偏移)需要 1.7971360683441 秒

回答by Slashback

I can't leave comments, but in regard to FastTrack's answer, also remember that the line ending may be only single character. I would suggest

我不能发表评论,但关于 FastTrack 的回答,还要记住行尾可能只是单个字符。我会建议

substr(trim($string), -1)

EDIT:My code below was edited by someone, making it not do what I indicated. I have restored my original code and changed the wording to make it more clear.

编辑:我下面的代码是由某人编辑的,使它没有按照我的指示进行。我已经恢复了我的原始代码并更改了措辞以使其更加清晰。

trim(or rtrim) will remove allwhitespace, so if you do need to check for a space, tab, or other whitespace, manually replace the various line endings first:

trim(或rtrim) 将删除所有空格,因此如果您确实需要检查空格、制表符或其他空格,请先手动替换各种行结尾:

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

回答by nektobit

As of PHP 7.1.0, negative string offsets are also supported. So, if you keep up with the times, you can access the last character in the string like this:

从 PHP 7.1.0 开始,还支持负字符串偏移量。所以,如果你跟上时代,你可以像这样访问字符串中的最后一个字符:

$str[-1]

DEMO

演示

At the request of a @mickmackusa, I supplement my answer with possible ways of application:

应@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)

回答by Xenonite

I'd advise to go for Gordon's solution as it is more performant than substr():

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

outputs something like

输出类似

 ---------------------------------- 
 10000000 repetitions...
 ----------------------------------

 substr() took 2.0285921096802seconds 
 array access took 1.7474739551544seconds

回答by FastTrack

Remember, if you have a string which was read as a line from a text file using the fgets()function, you need to use substr($string, -3, 1)so that you get the actual character and not part of the CRLF (Carriage Return Line Feed).

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

I don't think the person who asked the question needed this, but for me, I was having trouble getting that last character from a string from a text file so I'm sure others will come across similar problems.

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

回答by Faisal

You can find last character using php many ways like substr()and mb_substr().

您可以通过多种方式使用 php 找到最后一个字符,例如substr()mb_substr()

If you're using multibyte character encodings like UTF-8, use mb_substrinstead of substr

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

Here i can show you both example:

在这里,我可以向您展示两个示例:

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

LIVE DEMO

现场演示

回答by Petar Atanasov

A string in different languages including C sharp and PHP is also considered an array of characters.

包括 C 锐利和 PHP 在内的不同语言中的字符串也被视为字符数组。

Knowing that in theory array operations should be faster than string ones you could do,

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

$foo = "bar";


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

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

However, standard array functions like

但是,标准数组函数如

count();

will not work on a string.

不适用于字符串。