如何在两种模式之间复制文件行并存储在 PHP 中的数组中


How do I copy the lines of file in between two patterns and store in an array in PHP

我当前的PHP代码是:

$searchFor="Sum";
$handle=@fopen("assets/lib/basic.lib"); //this if my file consisting of sum structure
if($handle){
while(!feof($handle)){
    $buffer=fgets($handle);
    if(strpos($buffer,$searchFor)!==FALSE)
      $matches[]=$buffer;
    }
    fclose($handle);
}

这是basic.lib文件:

Sum: start
Sum: op1 =
Sum: op2 +
Sum: op *
Sum: end
Sub: start
Sub: op1 =
Sub: op2 -
Sub: end

上面的php代码有助于检索所有具有子字符串sum的行

但我想将basic.lib文件重新设计为:

Sum:start
output 1: Hello
output 2: world
Sum:end
Sub:start
output 1: Hello
output 2: Again
Sub:end

那么我现在如何在 $matches 数组中处理 Sum:start 和 Sum:end 之间的行。

提前致谢

具有

file函数的简单解决方案:

$arr = file("assets/lib/basic.lib");
$capture = false;
$needed_lines = [];
foreach ($arr as $line) {
    if (strpos($line, "Sum:start") !== false){
        $capture = true;
        continue;
    } elseif (strpos($line, "Sum:end") !== false) {
        $capture = false;
    }
    if ($capture){
        $needed_lines[] = $line;
    }
}
var_dump($needed_lines);
// the output:   
 array (size=2)
  0 => string 'output 1: Hello
' (length=17)
  1 => string 'output 2: world
' (length=17)

您可以将文本文件拆分为数组并检查每个元素中的特定字符串:

$filename = "txtfile.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$arr = explode(PHP_EOL, $contents);
foreach ($arr as $key => $value) {
    if (strpos($value, ':start') !== false || strpos($value, ':end') !== false) {
        unset($arr[$key]);
    }
}
$arr = array_values($arr);
print_r($arr);

输出为:

Array
(
    [0] => output 1: Hello
    [1] => output 2: world
)