如果你在一个句子的最后一个词之后,为什么不做这样的事情呢?
$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个单词字符串上的最后一个单词,你应该以不同的方式去做。