如何在包含字符串的文件行中查找并在该行的末尾添加一些内容

时间:2012-07-16 12:29:02

标签: php find

我有要编辑的文件包含:

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

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

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

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

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);

?>

答案 2 :(得分: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);

?>