我尝试了很多可能的解决方案,但它们都对我没有用。 最简单的一个:
$file = file('list.html');
array_pop($file);
这里好像什么都没做。我有做错什么吗?因为这是一个html文件所以情况不同吗?
我尝试了很多可能的解决方案,但它们都对我没有用。 最简单的一个:
$file = file('list.html');
array_pop($file);
这里好像什么都没做。我有做错什么吗?因为这是一个html文件所以情况不同吗?
<?php
// load the data and delete the line from the array
$lines = file('filename.txt');
$last = sizeof($lines) - 1 ;
unset($lines[$last]);
// write the new data to the file
file_put_contents('filename.txt', $lines);
unset($var[count($var) - 1])
不如 array_pop($var)
简洁优美。$implode($lines)
)$text = file_get_contents( 'FILE_PATH' );
$pos = strrpos( $text, PHP_EOL );
$text = substr( $text, 0, $pos );
file_put_contents( 'FILE_PATH', $text );
$text = file_get_contents( 'FILE_PATH' );
$offset = mb_substr( $text, -1 ) == PHP_EOL ? -2 : 0;
$pos = strrpos( $text, PHP_EOL, $offset );
$text = $offset === 0 ? substr( $text, 0, $pos ) : substr( $text, 0, $pos ) . PHP_EOL;
file_put_contents( 'FILE_PATH', $text );
$max
设置为您想要删除的行数。function trim_lines($path, $max) {
// Read the lines into an array
$lines = file($path);
// Setup counter for loop
$counter = 0;
while($counter < $max) {
// array_pop removes the last element from an array
array_pop($lines);
// Increment the counter
$counter++;
} // End loop
// Write the trimmed lines to the file
file_put_contents($path, implode('', $lines));
}
Call the function like this:
trim_lines("filename.txt", 1);
$path
可以是文件路径或文件名。在 PHP 中删除变量的第一行和最后一行:
使用 phpsh 交互式 shell:
php> $test = "line one\nline two\nline three\nline four";
php> $test = substr($test, (strpos($test, "\n")+1));
php> $test = substr($test, 0, strrpos($test, "\n"));
php> print $test;
line two
line three
你可能想表达的是“最后一个非空行”。如果是这样,请按照以下步骤操作:
请注意,在内容后面有三行空白行。这将在删除最后一行之前去除这些行:
php> $test = "line one\nline two\nline three\nline four\n\n\n";
php> $test = substr($test, 0, strrpos(trim($test), "\n"));
php> print $test;
line one
line two
line three
你只是在读取文件,现在需要写入文件
可以查看 file_put_contents
等函数