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

ale*_*rdy 7 php string

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

this.is.a.sample
this.is.another.sample.of.it
this.too
Run Code Online (Sandbox Code Playgroud)

我想做的是隔离最后一部分.所以我想要"样本",或"它",或"太".

实现这一目标的最有效方法是什么?显然有很多方法可以做到这一点,但哪种方式最好使用最少的资源(CPU和RAM).

Men*_*ual 25

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

echo end($contents); // displays 'it'
Run Code Online (Sandbox Code Playgroud)


Mik*_*ike 7

我知道这个问题是2012年的,但这里的答案都是低效的。PHP 中内置了字符串函数来执行此操作,而不必遍历字符串并将其转换为数组,然后选择最后一个索引,这对于完成一些非常简单的事情来说是大量的工作。

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

strrchr($string, '.'); // Last occurrence of '.' within a string
Run Code Online (Sandbox Code Playgroud)

我们可以将其与 结合使用substr,它本质上是根据位置切碎字符串。

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

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