1

我从 MySQL 数据库中提取了以下数据来创建标签。

休息

名称:RAJ
公司:ABC
订单号:101

订单详细信息:
项目1
第 20 项
第 3 项

休息

名称:RAJ
公司:ABC
订单号:101

订单详细信息:
2 x 项目 1
2 x 物品 2
2 x 物品 3

休息

名称:RAJ
公司:ABC
订单号:101

订单详细信息:
5 x 物品4
5 x 物品 5
5 x 物品 2

我编写了一些代码来查找 BREAK 在 PHP 中的位置,它可以生成如下所示的行号。

2
14
26
36

我想要一个文件的内容在一个文件中的第 2 行和第 14 行之间以及一个文件中的第 26 到 36 行之间。我正在使用 php 并尝试使用 shell_exec 函数中的 sed 但是如果我读取此输出并生成 sed 命令,我不会将前 2 个数字放在一起。

我所期待的如下。

sed -n 2,14p file1.txt
sed -n 26,36p file2.txt

在 php 或 shell 脚本中有什么建议吗?

4

1 回答 1

0

使用array_slice()获取数组中的范围。我的解决方案很难满足您的要求,这意味着每一行都是一个起始范围编号,然后是结束范围。

// the lines from which will be read
$lines = "1
5
16
26";
// split these numbers above into an array
$lines = explode(PHP_EOL, $lines);

// the source file where the ranges will be taken off
$file = file('file.txt');


for($i = 0; $i < count($lines); $i+=2) {
  $rangeStart  = $lines[$i];
  $rangeLength = $lines[$i+1] - $lines[$i];

  // slice out the ranges, beware the second parameter is the length not the offset!
  $ranges[] = array_slice($file, $rangeStart, $rangeLength);

}

print_r($ranges);

但是,如果可能的话,直接在源文件/文本/字符串(?)上自动执行它会容易 得多

$file = file('file.txt');
$len  = count($file);

$output  = array();
$current = array();
for($i = 0; $i < $len; $i++) {
  $data = trim($file[$i]);

  if ($data != 'BREAK') {
    $current[] = $data;
  } else {
    $output[] = implode(PHP_EOL, $current);
    $current  = array();
  }
}

print_r($output);
于 2012-04-25T19:28:54.157 回答