0

我正在创建一种搜索算法,它在文本文件中查找特定字符串,并使用一个作为起点,一个作为终点

在起点它触发一个函数开始将行复制到数组中,

function copy_line_to_array($line_to_copy, &$found_lines)
  {
  array_push($found_lines, $line_to_copy."<br>");
  }   

然后在端点上停止复制,直到找到下一个起点。

foreach($rows as $row => $data)
    {
    if(preg_match("/Start Point/", $data))
      {
      //Set the copy trigger to on
      $copy_line = "on";
      } 
   else if(preg_match("/End Point/", $data))
    {
     //Turn off the copy trigger until we find another 'Start Point' 
     $copy_line = "off";
     //We also want to copy the 'End Point' line though
     copy_line_to_array($data, $found_lines);
    }
  //If the trigger is set to on then call the function to copy the current line
  if($copy_line == "on")
    {   
    copy_line_to_array($data, $found_lines);
    }           
}

我想做的是每次找到“起点”时在$found_lines数组中创建一个数组。这将允许我单独处理每个从开始到结束的文本块,并在其中搜索不同的字符串。

如何在数组中为每个文本块创建一个新数组?

4

2 回答 2

1

调整算法,以便将行复制到“当前块”数组。每当您找到和结束点时,将当前块附加到主数组并开始一个新的:

$master = $chunk = [];
$copy_line = false;

foreach($rows as $row => $data)
{
    if(preg_match("/Start Point/", $data))
    {
        $copy_line = true;
    } 
    else if(preg_match("/End Point/", $data))
    {
        $copy_line = false;
        copy_line_to_array($data, $chunk);
        $master[] = $chunk;  // append chunk to master
        $chunk = [];         // start with fresh empty chunk next time
    }

    if($copy_line)
    {   
        copy_line_to_array($data, $chunk);
    }           
}
于 2013-10-04T09:10:56.257 回答
0
if($copy_line == "on")
{   
    $found_lines[] = $data
} 
于 2013-10-04T09:12:22.213 回答