我正在尝试在使用fgets()
读取文本文件时跳过第一行和最后一行。第一行可以通过 if(!$firstLine)
解决,但我不确定如何忽略最后一行,或者我的解决方案是否是最佳选择。
我正在尝试在使用fgets()
读取文本文件时跳过第一行和最后一行。第一行可以通过 if(!$firstLine)
解决,但我不确定如何忽略最后一行,或者我的解决方案是否是最佳选择。
fgets($file); //Ignore the first line
$line = fgets($file);
$next = fgets($file);
while ($next !== false) { //check the line after the one you will process next.
//This way, when $next is false, then you still have one line left you could process, the last line.
//Do Stuff
$line = $next;
$next = fgets($file);
}
$lines = file('http://www.example.com/');//or local file
unset($lines[0]);
unset($lines[count($lines)-1)]);
$new_file = implode('', $lines); //may want to use line break "\n" for the join
试试这个
$str= file_get_contents("file.txt");
$arr = preg_split ("\n",$str);
$n = count($arr);
$n是行数
$str="";
for($i=0;$i<$n;$i++){
if($i>0 && $i<($n-1)){ $str.=$arr[$i]}
}
/**Str without line 1 and final line */
不幸的是,file() 函数会将文件打开为“串行”流(不确定“串行”是否是正确的词),这意味着在检测到文件结尾之前,您必须读取整个文件。
$fp = fopen($path, 'r'); fseek($fp, -16); $end = fgets($fp);
应该返回文件的最后16个字节(如果至少有16个字节),而无需读取整个内容。 - lupatusfile
函数不会将文件作为流打开 - 它会读取其内容并将其作为行的数组
返回给您。 - lupatusarray_shift
将返回file
返回的数组的第一个元素,这样您将生成只有变量可以通过引用传递
。正确的方法是array_slice(file($path), 1, -1)
。 - lupatus