Reputation: 4516
I have file to edit that contains:
Categories,
Diamond,10,11,
Coal,21,21,
How to add string at the end of line containing "Diamond"?
What I have is code that can add string at the end of a file but don't know how to make it to add that string in specyfic line:
$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);
Upvotes: 1
Views: 2586
Reputation: 17000
<?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);
?>
Upvotes: 1
Reputation: 5846
I should have used an preg_replace
if the file content isn't too large.
$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);
Upvotes: 4
Reputation: 12721
all the previous posted solutions may fail when working on big files. here is one which works on files of any size. (should add some checks if files are readable and writeable etc.)
<?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);
?>
Upvotes: 3