You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中直接获取语句中的最后n个单词?

PHP获取字符串最后N个单词的简洁实现

我懂你想要的那种省心的实现方式——不用手动计算总单词数,直接指定N就能拿到最后几个单词对吧?给你几个比原来手动切片更优雅的方案:

最直接的方案:用array_slice的负数偏移量

array_slice支持传入负数作为起始位置,意思就是从数组末尾开始计数。比如要取最后5个单词,直接传-5就行,完全不用管前面有多少个单词,完美匹配你想要的“直接实现”需求:

<?php
$string = "This is an example to get last five words from this sentence";
$words = explode(" ", $string);
// 指定要获取的最后n个单词,这里n=5
$n = 5;
$lastNWords = array_slice($words, -$n);
echo implode(" ", $lastNWords);
// 输出结果:five words from this sentence
?>

如果需要同时保留前面的部分和最后n个部分,也可以用同样的思路,不用手动算切片起始点:

<?php
$string = "This is an example to get last five words from this sentence";
$words = explode(" ", $string);
$n = 5;
// 取除了最后n个之外的前面所有单词
$firstPart = array_slice($words, 0, -$n);
// 取最后n个单词
$lastPart = array_slice($words, -$n);

echo implode(" ", $firstPart) . "<hr/>" . implode(" ", $lastPart);
?>

处理含连续空格的情况

如果你的字符串里可能有多个连续空格(或者首尾空格),用explode(" ", $string)会产生空元素,这时候可以用正则分割来避免这个问题:

<?php
$string = "This is   an example with  multiple spaces   ";
// 用正则匹配一个或多个空白字符来分割,同时先trim掉首尾空格
$words = preg_split('/\s+/', trim($string));
$n = 3;
$lastNWords = array_slice($words, -$n);
echo implode(" ", $lastNWords);
// 输出结果:multiple spaces
?>

这个方案和只取最后一个单词的逻辑是延伸,但更通用,支持任意N值,完全符合你要的“最后n个单词”的需求。

内容的提问来源于stack exchange,提问作者Tim Paine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:14:01