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

10

我有很多符合相同规则的字符串:

this.is.a.sample
this.is.another.sample.of.it
this.too

我想要做的是分离出最后一部分。所以我想要 "sample",或者 "it",或者 "too"。

那么,最有效的方法是什么呢?显然有很多种方法可以实现,但是哪种方法使用最少的资源(CPU 和 RAM��最好呢?


strrchr 是一个不错的起点。另外还有 substr - drew010
我知道如何做到这一点,但我希望以最高效的方式快速地重复执行多次。 - alecwhardy
这不是一个很好的限定词吗?为什么不把它放到问题本身中呢? - deceze
更好的答案在这里:https://dev59.com/qGQn5IYBdhLWcg3wLkrL#17030851 - Jonathan Bergeron
6个回答

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

echo end($contents); // displays 'it'

这比使用strrchr和strrpos快吗? substr($string, strrchr($string, '.')+1) - Rein Baarsma
看起来是这样的:什么更有效率?。不过测试是使用PHP5进行的。 - user5446912

7

我知道这个问题是2012年的,但这里的答案都很低效。PHP内置了字符串函数来完成这个任务,而不需要遍历字符串并将其转换为数组,然后选择最后一个索引,这是一项非常简单的工作。

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

strrchr($string, '.'); // Last occurrence of '.' within a string

我们可以将这个与substr结合使用,它基本上根据位置来截取字符串。
$string = 'this.is.a.sample';
$last_section = substr($string, (strrchr($string, '-') + 1));
echo $last_section; // 'sample'

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

这是很好的建议,不过你的实际代码有一个小问题。strrchr返回给定字符之后和包括该字符在内的字符串部分,而不是数字索引。因此,你需要执行$last_section = substr(strrchr($string, '.'), 1);来获取字符后面的所有内容。 - Mark

3

http://us3.php.net/strpos

$haystack = "this.is.another.sample.of.it"; 
$needle = "sample"; 
$string = substr( $haystack, strpos( $haystack, $needle ), strlen( $needle ) ); 

3

只需要执行:

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

不建议这样做:PHP 注意:只应传递变量的引用。 - Daniel-KM
所以@Daniel-KM只需将该函数分成两行即可。 - Max Cuttins

0
$new_string = explode(".", "this.is.sparta");
$last_part = $new_string[count($new_string)-1];

echo $last_part;    // prints "sparta".

0
$string = "this.is.another.sample.of.it";
$result = explode('.', $string); // using explode function

print_r($result); // whole Array

会给你

result[0]=>this;
result[1]=>is;
result[2]=>another;
result[3]=>sample;
result[4]=>of;
result[5]=>it;

显示任何你想要的(例如:echo result[5];


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接