我从MySQL数据库中提取了以下数据来创建标签。
BREAK Name:RAJ Company:ABC Order Number:101 Order Details: Item1 Item20 Item3 BREAK Name:RAJ Company:ABC Order Number:101 Order Details: 2 x Item1 2 x Item2 2 x Item3 BREAK Name:RAJ Company:ABC Order Number:101 Order Details: 5 x Item4 5 x Item5 5 x Item2
我写了一些代码来找到BREAK在PHP中的位置,它可以生成如下的行号。
2 14 26 36
我想要一个文件,用于一个文件中第2行和第14行之间的内容,以及一个文件中26到36之间的内容。我正在使用php并尝试使用sed from shell_exec函数但是如果我读取此输出并生成sed命令,我不会得到前2个数字。
我期待的是下面的内容。
sed -n 2,14p file1.txt sed -n 26,36p file2.txt
在php或shell脚本中有任何建议吗?
答案 0 :(得分: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);