如何删除文件中的所有行,直到一个特定的单词出现PHP



我有多个文件包含相同的文本结构。我现在正在尝试删除所有行,直到一行以特定单词开头。这是其中一个文件的一部分:

Test        Sampertant
ALL         5784
COMMENT     This files contains information about infomarxinc
COMMENT     Companie located in USA
FEATURES               Location/Qualifiers
A               lines (7709..2170)
3'try           complement(7676..7678)
/note="stop"
/label=STOP
B               lines (7679..7708)
/note="stop"
/label=start
PAST
1 talian and American multinational corporation and is the world’s 
50 eighth largest auto maker.The group was established in late 2014

我只想保留PAST之后的行我已经写了以下代码来做这个

$lines = file($newname);
# Loop through the array
foreach($lines as $line) { 
$seq = trim($line);
# Find all lines starting with a number
if (preg_match('/^d/', $seq)){ 
# Replace all number with | 
$seq = preg_replace('/[0-9]+/', '', $seq);
$seq = preg_replace('/s/',"",$seq);
# Store in string
$out .= $seq;
} 
### Read lines into file ###
$f = fopen($newname, "w");
fwrite($f, $out);
fclose($f);
} 

对于大多数文件,它一直有效,直到我得到这个文件。PART前面的一行以3’try开头。在我的最终结果中,3分球也被加上了,但我不想这样我现在如何删除所有行,直到我的行以PAST开头,然后执行我的代码来查找所有以数字开头的行只保留此文件的这些行:

1 talian and American multinational corporation and is the world’s 
50 eighth largest auto maker.The group was established in late 2014

您只需添加一个额外的逻辑位,即可在写出编号行之前先找到"PART"行:

$lines = file($newname);
$found = false;
// Loop through the array
foreach($lines as $line) { 
$seq = trim($line);
if( $seq == "PAST" )
$found = true;
// Find all lines starting with a number
if ($found && preg_match('/^d/', $seq)){ 
# Replace all number with | 
$seq = preg_replace('/[0-9]+/', '', $seq);
$seq = preg_replace('/s/',"",$seq);
# Store in string
$out .= $seq;
} 
// Read lines into file
$f = fopen($newname, "w");
fwrite($f, $out);
fclose($f);
} 

也许我遗漏了一些东西,但以下内容应该有效:

$raw = file_get_contents($filename);
if (! $raw) {
echo 'no valid data';
exit;
}
$cut = strpos($raw,'PAST');
if (! $cut) {
echo 'PAST not found in file';
exit;
}
echo substr($raw,$cut + 5);
exit;

正如你所说的,所有文件都有相同的结构:

$raw = file_get_contents($filename);
if (! $raw) {
echo 'no valid data';
exit;
}
$lines = explode("n",$raw); // assume n as the line return
$lines = array_splice($lines,13);
echo join("n",$lines);
exit;

最新更新