1

我有要编辑的文件,其中包含:

Categories,
Diamond,10,11,
Coal,21,21,

如何在包含“钻石”的行尾添加字符串?

我所拥有的是可以在文件末尾添加字符串但不知道如何使其在特定行中添加该字符串的代码:

$function_Result = mysql_fetch_row($function_Ask, 0);

$file_To_Edit = "item_Data.csv";
$opened_File = fopen($file_To_Edit, 'w') or die("Error. Code:2 - Can not open file $file_To_Edit");

$string_Data = $function_Result[0] . ",";
fwrite($opened_File, $string_Data);
fclose($opened_File);
4

3 回答 3

4

preg_replace如果文件内容不是太大, 我应该使用。

$content = file_get_contents('file.txt');
/* in case of unwanted \r */ $content = str_replace("\r", '', $content);
$content = preg_replace("#^(Diamond.*)$#m", '$1' . $append, $content);
file_put_contents('file.txt', $content);
于 2012-07-16T12:41:25.397 回答
3

在处理大文件时,所有以前发布的解决方案都可能会失败。这是一种适用于任何大小文件的方法。(应该添加一些检查文件是否可读和可写等)

<?php
$file = "item_Data.csv"
$tmpFile = $file .".tmp";

$in = fopen($file, "r")
$out = fopen($tmpFile, "w")

while (($buffer = fgets($in)) !== false) {

    if (preg_match('/my search pattern/', $buffer )) {

        $buffer .= 'append this to the matched line';
    }

    fwrite($out, $buffer);
}

fclose($in);
fclose($out);
unlink($file);
rename($tmpFile, $file);

?>
于 2012-07-16T12:50:20.480 回答
1
<?php 

$string_Data = '444555';

$file_To_Edit = "./11.csv";

$opened_File = file($file_To_Edit) or die("Error. Code:2 - Can not open file $file_To_Edit"); // Reads entire file into array of file lines

$diamond_lines = preg_grep('#^Diamond#', $opened_File); // Finds array with line started with 'Diamonds'

foreach(array_keys($diamond_lines) as $key) { // Runs 'Diamonds' array

    $opened_File[$key] = substr($opened_File[$key], 0, -1) . $string_Data; // Removes the last character from 'Diamond' line (new line chracter) and adds $string_Data variable at the end

}

//var_dump($opened_File);

$f = fopen($file_To_Edit, 'w');

fwrite($f, implode("\n", $opened_File)); // Writes new .CSV file

fclose($f);

?>
于 2012-07-16T12:47:18.827 回答