[英]How to remove all lines in file till a specific word occures 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'try也被添加但我不想那樣。 我現在如何刪除所有行,直到我的行開始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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.