获取字符串的最后一个单词 [英] Get the last word of a string
问题描述
我已经尝试了一些方法来使最后一部分发挥作用 我做到了:
I have tried a few things to get a last part out I done this:
$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]})
第一个无效,第二个返回一个数组,但确实需要一个字符串.
The first one won't work and the second returns an array but a realy need string.
推荐答案
如果您紧接句子中的最后一个单词,为什么不这样做呢?
If you're after the last word in a sentence, why not just do something like this?
$string = 'Sim-only 500 | Internet 2500';
$pieces = explode(' ', $string);
$last_word = array_pop($pieces);
echo $last_word;
我不建议使用正则表达式,因为除非有必要,否则不要使用正则表达式.
I wouldn't recommend using regular expressions as it's unnecessary, unless you really want to for some reason.
$string = 'Retrieving the last word of a string using PHP.';
preg_match('/[^ ]*$/', $string, $results);
$last_word = $results[0]; // $last_word = PHP.
他们提供的substr()
方法可能更好一些
The substr()
method they gave is probably abit better
$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个单词字符串中的最后一个单词,那么您可能应该以其他方式来处理它.
it is faster, although it really doesn't make that much of a difference on things like this. If you're constantly needing to know the last word on a 100,000 word string, you should probably be going about it in a different way.
这篇关于获取字符串的最后一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!