在生成器函数中使用explode在PHP中迭代长字符串
我使用一个PHP函数来解析一个很长的字符串(shell_exec命令的输出)。目前,该函数如下所示,运行良好在生成器函数中使用explode在PHP中迭代长字符串,php,string,iterator,generator,explode,Php,String,Iterator,Generator,Explode,我使用一个PHP函数来解析一个很长的字符串(shell_exec命令的输出)。目前,该函数如下所示,运行良好 /** * @param string $result Output of shell command * @return array $lines each line of output in array */ public function getLines($result) { $lines = []; $expl = explode(PHP_EOL, $r
/**
* @param string $result Output of shell command
* @return array $lines each line of output in array
*/
public function getLines($result)
{
$lines = [];
$expl = explode(PHP_EOL, $result);
foreach ($expl as $line) {
$lines[] = $this->funcFormatLine($line);
}
return $lines;
}
现在,我开始使用这个函数,它看起来是一个很好的使用它进行重构的用例,因为explode输出的数组很大,并且会消耗一些内存
我想要的是:
/**
* @param string $result Output of shell command
* @return string $line one line of output until end_of_line
*/
public function getLines($result)
{
$line = fancy_func_to_get_all_before_end_of_line_without_array(PHP_EOL, $result);
yield $line;
}
//somewhere in the function
foreach (getLines($result) as $line) {
doThings($this->funcFormatLine($line));
}
在第一种情况下,我有两个包含大量信息的数组($expl
和$lines
),在第二种情况下,我尝试使用生成器来避免将这些内存用于数组
我是否以错误的方式使用了发电机的概念?如果没有,是否可以在不分解字符串的情况下实现它,然后生成$expl[$key]
我尝试使用substr($string,$pos,strpos($string,PHP_EOL,$pos))其中$pos
是字符串的位置,但我只能使用它调用一次getLines
信息:
PHP 5.6从文本中提取行时如何使用生成器的示例。它有一个循环来逐个查找行,并使用
yield
一次一个地传回每个段
function getLines( $result ) {
$start = 0;
while (($end = strpos($result, PHP_EOL, $start)) !== false) {
$line = trim(substr($result, $start, $end - $start));
yield $line;
$start = $end+1;
}
}
foreach ( getLines($test) as $line) {
echo ">".$line."<".PHP_EOL;
}
函数获取行($result){
$start=0;
while(($end=strpos($result,PHP_EOL,$start))!==false){
$line=trim(substr($result,$start,$end-$start));
收益率$line;
$start=$end+1;
}
}
foreach(getline($test)作为$line){
echo“>”“$line.”在内存中保留此“非常长的字符串”可能会在适当的时候导致其自身的问题。我建议将shell_exec()
切换为,然后将生成器置于yield fgets($pipes[1])
,在命令运行时直接从命令的stdout中读取行。实际上,我无法编辑从shell返回输出的代码,因为它在系统的许多其他部分中使用,但无论如何,感谢您的提示,也许我尝试为它创建一个专用函数。