微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 获取字符串的最后一个单词

我已经尝试了一些事情来获得最后一部分
我这样做了:

$string = 'Sim-only 500 | Internet 2500';
preg_replace("Sim-Only ^([1-9]|[1-9][0-9]|[1-9][0-9][0-9][0-9])$| Internet ","",$string
AND
preg_match("/[^ ]*$/","",{abo_type[1]})

一个不起作用,第二个返回一个数组,但真正需要字符串.

解决方法:

如果你在句子的最后一个单词之后,为什么不做这样的事呢?

$string = '​Sim-only 500 ​| Internet 2500';
$pieces = explode(' ', $string);
$last_word = array_pop($pieces);

echo $last_word;

我不建议使用正则表达式,因为它是不必要的,除非你真的想要出于某种原因.

$string = 'Retrieving the last word of a string using PHP.';
preg_match('/[^ ]*$/', $string, $results);
$last_word = $results[0]; // $last_word = PHP.

他们给出的substr()方法可能更好

$string = 'Retrieving the last word of a string using PHP.';
$last_word_start = strrpos($string, ' ') + 1; // +1 so we don't include the space in our result
$last_word = substr($string, $last_word_start); // $last_word = PHP.

它更快,虽然它确实没有在这样的事情上产生那么大的差异.如果您经常需要知道100,000字符串的最后一个字,那么您应该以不同的方式处理它.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐