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

如何使用PHP实现字符串按三个单词为单位的滑动分组拆分

PHP 实现三单词滑动拆分功能

实现逻辑完全对齐你提供的Java版本,代码如下:

<?php
$myString = "This is an example of what I need.";
// 按任意多个空白字符分割字符串为单词数组,过滤空元素避免前后空格影响结果
$words = preg_split('/\s+/', $myString, flags: PREG_SPLIT_NO_EMPTY);
$wordCount = count($words);

for ($i = 0; $i < $wordCount; $i++) {
    $threeWords = '';
    if ($i == $wordCount - 1) {
        $threeWords = $words[$i];
    } elseif ($i == $wordCount - 2) {
        $threeWords = $words[$i] . ' ' . $words[$i + 1];
    } else {
        $threeWords = $words[$i] . ' ' . $words[$i + 1] . ' ' . $words[$i + 2];
    }
    // 可直接输出,也可存入数组做后续处理
    echo $threeWords . PHP_EOL;
}
?>

如果想要更简洁的写法,可以用array_slice直接截取指定长度的元素再拼接,不需要手动写分支判断:

<?php
$myString = "This is an example of what I need.";
$words = preg_split('/\s+/', $myString, flags: PREG_SPLIT_NO_EMPTY);
$wordCount = count($words);

for ($i = 0; $i < $wordCount; $i++) {
    // 从i位置开始截取最多3个元素,用空格拼接后输出
    echo implode(' ', array_slice($words, $i, 3)) . PHP_EOL;
}
?>

两种写法运行后都可以得到你预期的输出:

This is an
is an example
an example of
example of what
of what I
what I need.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:39:03