请问有人能告诉我如何跳过文件的第一行和最后一行吗?我写了两个函数来返回文件的第一行和最后一行,但我需要在头部和尾部之间的行!
function get_file_header($file) {
return fgets($file);
}
function get_file_tail($file){
while (( $line = fgets($file) )){
$fin = $line;
}
return $fin;
}
file
函数将行读入数组,然后使用array_slice
函数执行删除操作:function get_file_tail($filepath){
// Read file as lines into an array
$lines = file($filepath);
// Remove first and last line
$lines = array_slice($lines, 1, count($lines)-2);
// Convert to string (if array is not useful for you) and return it
return implode(PHP_EOL, $lines);
}
示例调用:
echo get_file_tail("http://websitetips.com/articles/copy/lorem/ipsum.txt");
get_file_tail
,为什么它要移除第一行和最后一行呢?看起来这样做并不合乎逻辑。 - A.L我已经通过以下方式解决了我的问题:
function get_file_details($file){
$details = array();
if ($file) {
while (($line = fgets($file)) !== false) {
array_push($details, $line);
}
fclose($file);
}
$info_file = array("header" => $details[0], "details" => remove_first_last($details) , "end" => end($details) );
return $info_file;
}
function remove_first_last($array){
将数组的第一个和最后一个元素移除
array_shift($array);
array_pop($array);
return $array;
}
get_file_tail
函数,请阅读关于数组和如何删除数组的最后一项。当文件只有1行时,您仍需要控制发生的情况。 - Sergi Juanola