我从MySQL数据库中提取了以下数据来创建标签。
破姓名:拉杰公司:农行订货号:101订单详情:项目1项目20项目3破姓名:拉杰公司:农行订货号:101订单详情:2 x 项目12 x 项目22 x 项目3破姓名:拉杰公司:农行订货号:101订单详情:5 x 项目45 x 项目55 x 项目2
我写了一些代码来查找 BREAK 在 PHP 中的位置,它可以生成如下所示的行号。
2142636
我想要一个文件,其中包含一个文件中第 2 行和第 14 行之间的内容,一个文件中介于第 2 行到 36 行之间的内容。我正在使用 php 并尝试从函数中使用 sed shell_exec但是如果我读取此输出并生成 sed 命令,我不会一起获得前 2 个数字。
我期待的是下面。
sed -n 2,14p 文件1.txtsed -n 26,36p 文件2.txt
在 php 或 shell 脚本中有什么建议吗?
使用 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);