2012-07-16 57 views
1

我有文件的最后添加一些编辑包含:如何找到包含字符串文件中的行,并在该行

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

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

我有的是代码,可以在文件的末尾添加字符串,但不知道如何使它以添加字符串specyfic行:

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

什么是'$ function_Result'? – j0k 2012-07-16 12:33:34

+0

它是一个字符串,我将添加:'$ function_Result = mysql_fetch_row($ function_Ask,0);' – 2012-07-16 12:36:50

回答

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); 
+0

+1 Sod,我没有想到使用正则表达式。您的解决方案比我的更好 – Hubro 2012-07-16 12:42:52

+0

该文件将很大,包含80行非常长的字符串(非常长) – 2012-07-16 12:43:38

+0

如果它不是几兆字节,这仍然是快速的 – Hubro 2012-07-16 12:45:05

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

?> 
+0

为什么它输出数组(18){[0] =>字符串(13)“Categories,”[1] => string(1)“”[2] => string(1)“”[3] => string(1)“”[4] => string(1)“”[5] => string(1)“”[6] => string(1)“”[7] => string(1)“” [8] => string(1)“”[9] => string(1)“”[10] => string(1)“”[11] => string(1)“”[12] => string (1)“”[13] => string(1)“”[14] => string(1)“”[15] => string(1)“”[16] => string(30) 10,11,583583583583582“[17] =>字符串(11)”Coal,21,21,“}'? – 2012-07-16 15:15:35

+0

对不起,忘了发表评论'var_dump($ opened_File);' - 它转储'$ opened_File'变量。修改了我的答案。 – 2012-07-18 05:24:21

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

?> 
+0

感谢我用大文件示例来补充我的答案 – 2012-07-16 12:52:14

+0

如何在包含“Diamond”的行的preg_match中匹配包含“Diamond”的行并将缓冲区配置为在包含“Diamond”的行的末尾写入字符串? – 2012-07-16 15:09:53

相关问题