如何在PHP生成器函数中使用explode迭代超长字符串?
Convert Your Shell Output Parser to a PHP Generator
Great call switching to a generator here—this is perfect for handling large shell command outputs without loading everything into memory at once. Here's how to refactor your getLines() function to use a generator, plus some context on why this works better:
Refactored Generator Version
/** * @param string $result Output of shell command * @return \Generator Yields each formatted line of output */ public function getLines(string $result): \Generator { // Use strtok to split the string line by line without creating a full array first $line = strtok($result, PHP_EOL); while ($line !== false) { // Yield the formatted line instead of storing it in an array yield $this->funcFormatLine($line); // Get the next line $line = strtok(PHP_EOL); } }
Why This Is Better Than the Original Array Approach
- Memory Efficiency: Your original function first splits the entire output string into an array with
explode(), which creates a full copy of every line in memory. For ultra-long outputs, this can lead to unnecessary memory bloat. The generator usesstrtok()to process one line at a time, so only a single line is in memory at any point. - Lazy Execution: The generator doesn't process any lines until you start iterating over it. This means if you only need the first N lines, you don't waste time processing the rest.
How to Use the Generator
You can iterate over it directly with a foreach loop (just like an array):
$shellOutput = shell_exec('your-long-running-command'); foreach ($this->getLines($shellOutput) as $formattedLine) { // Do something with each formatted line echo $formattedLine . PHP_EOL; }
If you ever need to convert the generator's output back to an array (for cases where you need random access), you can use iterator_to_array():
$formattedLinesArray = iterator_to_array($this->getLines($shellOutput));
This keeps the core functionality of your original function but optimizes it for large datasets—exactly what generators are designed for!
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

