这是我的代码
<?php
$filename = 'names.txt';
$file = fopen($filename, 'w');
fwrite($file, implode(", ", $filename));
?>
my names.txt文件数据是这样的
saad
Alex
Ashmil
Shumail
Fredrik
我想在每个名字后面加上一个问号,除了最后一个。但我收到一个错误的"错误的参数传递给内爆函数"…告诉我现在该怎么办?
预期output
应
saad, Alex, Ashmil, Shumail
你可以使用这个代码:)
<?php
$filename = 'names.txt';
$file_read = fopen($filename, 'r');
$content = fread($file_read, filesize($filename));
$content = trim(preg_replace('/'s's+/', ' ', $content));
$pieces = explode(" ", $content);
$file_write = fopen($filename, 'w');
fwrite($file_write, implode(", ", $pieces));
fclose($file_read);
fclose($file_write);?>
这对我有用:)
<?php
$file = 'names.txt';
$array = file($file); // Creates an array of each line
$array = array_slice($array,0,-1); // Pops the last element of an array
$string = implode(','.PHP_EOL, $array); // Implode
file_put_contents($file, str_replace("'n","",$string));
?>
并给出了我期望的输出…
感谢@hamza, @Vivek和其他所有人。
也可以试试这个。它正在工作......
<?php
$file = 'names.txt';
$array = file($file); // Creates an array of each line
$array = array_slice($array,0,-1); // Pops the last element of an array
$string = implode(',', $array); // Implode
file_put_contents($file, str_replace("'n","",$string));
?>
就用file()
:
$file = 'names.txt';
$array = file($file); // Creates an array of each line
array_pop($array); // Remove the last value of the array
$string = implode(', ', $array); // Implode
file_put_contents($file, $string); // Write to file
使用:-
$file = 'names.txt';
$array = file($file); // Creates an array of each line
$array = array_slice($array,0,-1); // Pops the last element of an array
$string = implode(','.PHP_EOL, $array); // Implode
file_put_contents($file, str_replace(PHP_EOL,"",$string));
输出: -
saad, Alex, Ashmil, Shumail