3

这是我的代码

<?php

  $filename =  'names.txt';
  $file = fopen($filename, 'w');
  fwrite($file, implode(", ", $filename));

?>

我的names.txt文件数据是这样的

saad
Alex
Ashmil
Shumail
Fredrik

我只想在除最后一个名称之外的每个名称后加上一个 qoma。. 但我收到“传递给内爆函数的参数错误”的错误。告诉我现在该怎么办?

预计output应该是

saad, Alex, Ashmil, Shumail

4

5 回答 5

2

您可以使用此代码:)

<?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);?>
于 2013-05-30T09:22:24.177 回答
2

这对我有用:)

    <?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 和其他所有人..

于 2013-05-30T09:42:43.903 回答
1

只需使用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
于 2013-05-30T08:44:43.423 回答
1

用这个:-

$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
于 2013-05-30T09:05:37.487 回答
1

也试试这个。它工作......

<?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));


?>
于 2013-05-30T09:47:28.583 回答