如何在PHP中获取字符串的最后一部分

如何在PHP中获取字符串的最后一部分,php,string,Php,String,我有许多字符串遵循相同的约定: this.is.a.sample this.is.another.sample.of.it this.too 我想做的是隔离最后一部分。所以我想要“样品”,或“它”,或“太” 最有效的方法是什么。显然有很多方法可以做到这一点,但哪种方法使用最少的资源(CPU和RAM)才是最好的 我会给你 result[0]=>this; result[1]=>is; result[2]=>another; result[3]=>sample; resul

我有许多字符串遵循相同的约定:

this.is.a.sample
this.is.another.sample.of.it
this.too
我想做的是隔离最后一部分。所以我想要“样品”,或“它”,或“太”

最有效的方法是什么。显然有很多方法可以做到这一点,但哪种方法使用最少的资源(CPU和RAM)才是最好的

我会给你

result[0]=>this;
result[1]=>is;
result[2]=>another;
result[3]=>sample;
result[4]=>of;
result[5]=>it;
显示您想要的任何一个(例如,
回显结果[5];

只需执行以下操作:

$string = "this.is.another.sample.of.it";
$parts = explode('.', $string);
$last = array_pop(parts);

我意识到这个问题来自2012年,但这里的答案都是无效的。PHP中内置了字符串函数来实现这一点,而不必遍历字符串并将其转换为数组,然后选择最后一个索引,这是一项非常简单的工作

以下代码获取字符串中最后出现的字符串:

strrchr($string, '.'); // Last occurrence of '.' within a string
我们可以将其与
substr
结合使用,substr本质上是根据位置将字符串切碎

$string = 'this.is.a.sample';
$last_section = substr($string, (strrchr($string, '-') + 1));
echo $last_section; // 'sample'

注意
strrchr
结果上的
+1
;这是因为
strrchr
返回字符串中字符串的索引(从位置0开始),因此真正的“位置”始终为1个字符打开。

是一个很好的起点。我也知道如何做到这一点,但我希望最有效的方法能让这种情况快速发生很多次。这不是一个很好的问题本身的限定词吗?最好的答案是:这真的比使用strrchr和strrpos快吗?substr($string,strrchr($string,'.')+1)似乎是这样的:。不过,测试是用PHP5完成的。不建议这样做:
PHP注意:只能通过引用传递变量。
So@Daniel KM将函数分成两行。这是一个很好的建议,尽管实际代码中存在一个小问题。strrchr返回包含给定字符的字符串部分,而不是数字索引。所以您需要执行$last_section=substr(strrchr($string,'.'),1);去拿所有的东西。
result[0]=>this;
result[1]=>is;
result[2]=>another;
result[3]=>sample;
result[4]=>of;
result[5]=>it;
$string = "this.is.another.sample.of.it";
$parts = explode('.', $string);
$last = array_pop(parts);
strrchr($string, '.'); // Last occurrence of '.' within a string
$string = 'this.is.a.sample';
$last_section = substr($string, (strrchr($string, '-') + 1));
echo $last_section; // 'sample'