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

标签 php string

我已经尝试了一些方法来完成最后一部分 我这样做了:

$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/

相关文章:

php - 高级用户如何使用php来控制普通用户的功能?

javascript - 显示所选文件的名称

python - 在外部应用程序中打印字符串(python 3.1)

java - 替换java字符串中的正则表达式

swift - Swift 在使用 var 时是否有二次字符串连接?

php - 将 Laravel 查询结果转换为类

php - 无法在 centos 5.8 中安装 bcompiler,出现无法解压/tmp/bcompiler 的错误

php - PHP 数组中最大值的位置

iOS 获取两个字符串之间的字符串

java - 查找不同行星上的年龄