我已经尝试了一些方法来完成最后一部分 我这样做了:
$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 字串上的最后一个字,那么您可能应该以不同的方式处理它。
关于php - 获取字符串的最后一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18612872/