我有很多符合相同规则的字符串:
this.is.a.sample
this.is.another.sample.of.it
this.too
我想要做的是分离出最后一部分。所以我想要 "sample",或者 "it",或者 "too"。
那么,最有效的方法是什么呢?显然有很多种方法可以实现,但是哪种方法使用最少的资源(CPU 和 RAM��最好呢?
我有很多符合相同规则的字符串:
this.is.a.sample
this.is.another.sample.of.it
this.too
我想要做的是分离出最后一部分。所以我想要 "sample",或者 "it",或者 "too"。
那么,最有效的方法是什么呢?显然有很多种方法可以实现,但是哪种方法使用最少的资源(CPU 和 RAM��最好呢?
$string = "this.is.another.sample.of.it";
$contents = explode('.', $string);
echo end($contents); // displays 'it'
我知道这个问题是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 开始),所以真正的“位置”始终要多一个字符。$haystack = "this.is.another.sample.of.it";
$needle = "sample";
$string = substr( $haystack, strpos( $haystack, $needle ), strlen( $needle ) );
只需要执行:
$string = "this.is.another.sample.of.it";
$parts = explode('.', $string);
$last = array_pop(parts);
PHP 注意:只应传递变量的引用。
- Daniel-KM$new_string = explode(".", "this.is.sparta");
$last_part = $new_string[count($new_string)-1];
echo $last_part; // prints "sparta".
$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];
)