PHP实现句子按固定词数从左到右滑动分组(支持5000词)
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

