我有行
abc
def
ghi
jkl
mno
pqr
xyz
我想取前4行并删除它们?
我正在使用文件
$datafile="/var/www/html/test/data/$data";
$fp = fopen($datafile,"r");
我被困在这里!!如何移动指针,如何使用数组或任何缓冲区?
答案 0 :(得分:0)
$array = file("/var/www/html/test/data/$data");
$array = array_slice($array, 4);
答案 1 :(得分:0)
您可以使用file_get_contents()
获取文件的内容,然后使用preg_split()
将其转换为数组。一旦你有一排线;只需使用array_slice()
从您想要的索引中切割数组... 在您的情况下,4 。下面的代码显示了......
<?php
// THE TEXT FILE TO BE READ:
$targetFile = "/var/www/html/test/data/$data";
// GET THE CONTENTS OF THE FILE & STORE IT IN A VARIABLE (IF IT EXISTS)
$strFileContents = null;
if(file_exists($targetFile)){
$strFileContents = file_get_contents($targetFile);
}
// EVERY LINE IN A IS TERMINATED BY A NEW LINE CHARACTER.... WE KNOW THAT.
// SO WE SPLIT THE CONTENTS OF THE FILE USING THIS KNOWLEDGE...
if(!is_null($strFileContents)){
$arrFileLines = preg_split("#\n#", $strFileContents);
// SELECT ALL ELEMENTS FROM THE 4TH ELEMENT TILL THE END
$arrResultant = array_slice($arrFileLines, 4);
// CONVERT THE ARRAY BACK TO STRING...
$strBuffer = implode("\n", $arrResultant);
// RE-SAVE THE FILE BACK...
file_put_contents($targetFile, $strBuffer);
}
甚至更简洁;
<?php
// THE TEXT FILE TO BE READ:
$targetFile = "/var/www/html/test/data/$data";
if(file_exists($targetFile)){
$arrFileLines = file($targetFile);
if(!empty($arrFileLines) && count($arrFileLines) > 4){
// SELECT ALL ELEMENTS FROM THE 4TH ELEMENT TILL THE END
$arrResultant = array_slice($arrFileLines, 4);
// CONVERT THE ARRAY BACK TO STRING...
$strBuffer = implode("", $arrResultant);
// RE-SAVE THE FILE BACK...
file_put_contents($targetFile, $strBuffer);
}
}
干杯......祝你好运; - )