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

PHP实现句子按固定词数从左到右滑动分组(支持5000词)

Efficient Sliding 3-Word Grouping for Large Text (Up to 5000 Words)

Hey there! Let's fix that sliding word grouping problem you're working on. First, let's clarify why your original code didn't work: array_chunk() splits the array into non-overlapping chunks of 3 words, which gives you disconnected groups instead of the overlapping sliding windows you need.

For handling up to 5000 words efficiently, we need an O(n) time complexity approach—no unnecessary array operations, just straightforward iteration. Here are a few optimized solutions tailored to your needs:

Solution 1: Fixed 3-Window (Fastest for Exact 3-Word Groups)

This avoids array slicing entirely by directly accessing array indices, making it the most efficient option for your fixed 3-word requirement:

$inputText = "I am in love with you"; // Replace with your full text
$words = explode(" ", $inputText);
$wordCount = count($words);
$result = [];
$windowSize = 3;

// Only proceed if we have enough words for at least one window
if ($wordCount >= $windowSize) {
    // Loop through every valid starting index for a sliding window
    for ($i = 0; $i <= $wordCount - $windowSize; $i++) {
        // Build the 3-word string and wrap in span
        $result[] = sprintf("<span>%s %s %s</span>", $words[$i], $words[$i+1], $words[$i+2]);
    }
}

// Output the result with line breaks
echo implode("\n", $result);

Solution 2: Dynamic Window Size (Supports Any Window Length)

If you might need to adjust the window size later (say, 2 or 4 words instead of 3), this flexible version still stays efficient for large datasets:

$inputText = "I am in love with you";
$words = explode(" ", $inputText);
$wordCount = count($words);
$result = [];
$windowSize = 3; // Adjust this value as needed

if ($wordCount >= $windowSize) {
    for ($i = 0; $i <= $wordCount - $windowSize; $i++) {
        $windowString = "";
        // Build the window string by iterating through the current window
        for ($j = 0; $j < $windowSize; $j++) {
            $windowString .= ($j > 0 ? " " : "") . $words[$i + $j];
        }
        $result[] = sprintf("<span>%s</span>", $windowString);
    }
}

echo implode("\n", $result);

Why This Works for 5000 Words

Both solutions run in linear time (O(n))—for 5000 words, that's only 4998 iterations of the outer loop. Memory usage is also minimal: we're just storing the final string outputs, no large intermediate arrays. This will handle your large text input without performance lag.

Example Output

For your sample input I am in love with you, both solutions will output:

<span>I am in</span>
<span>am in love</span>
<span>in love with</span>
<span>love with you</span>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:28:02