猿问

如何替换文本文件中字符串的前半部分

我有一个包含数据并由逗号分隔符分隔的文本文件。这个文本文件的一个例子就像User,data,date日期的值是在输入数据时设置的。如果我想删除这行数据,是否可以做一个str_replacejustUser,data然后让它被替换为空。我不太熟悉str_replace在替换某些行时的工作原理,除了它是否是确切值。


我在问什么的例子。


文本文件: Austin,12,1:23:08pm


代码:


$content = file_get_contents('');

str_replace("Austin,12","",$content);

file_put_contents('');

因此,我没有获取该行中的所有数据,而是排除了它的最后一行。如果需要更多解释,我会编辑帖子。谢谢!


侃侃无极
浏览 194回答 2
2回答

红颜莎娜

使用fgetcsv()和假设这样的输入文件tst.dat(一个 csv 文件)Austin,12,1:23:08pmSmith,13,2:23:08pmJones,14,3:23:08pm和这样的代码<?phpif (($input = fopen("tst.dat", "r")) !== FALSE) {&nbsp; &nbsp; if (($output = fopen("new.dat", "w")) !== FALSE) {&nbsp; &nbsp; &nbsp; &nbsp; while (($line = fgetcsv($input, 1000, ",")) !== FALSE) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //echo $line[0] . ', ' . $line[1] . ', ' . $line[2] . PHP_EOL;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fwrite($output, $line[2] . PHP_EOL);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fclose($output);&nbsp; &nbsp; }&nbsp; &nbsp; fclose($input);}你会得到一个new.dat像这样调用的输出文件1:23:08pm2:23:08pm3:23:08pm并且只影响文件中的特定行<?phpif (($input = fopen("tst.dat", "r")) !== FALSE) {&nbsp; &nbsp; if (($output = fopen("new.dat", "w")) !== FALSE) {&nbsp; &nbsp; &nbsp; &nbsp; while (($line = fgetcsv($input, 1000, ",")) !== FALSE) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($line[0] == 'Austin'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // write only the last bit&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fwrite($output, $line[2] . PHP_EOL);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // by default write the complete line&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fputcsv($output, $line);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fclose($output);&nbsp; &nbsp; }&nbsp; &nbsp; fclose($input);}

慕哥6287543

假设您创建了一个名为“file”的文本文件,然后在它上面有一个文本“Austin,12,1:23:08pm”。以下代码应该适合您。//read the text file$textfile_data='';$textfile_name='file.txt';$fh = fopen("$textfile_name",'r');while ($line = fgets($fh)) {&nbsp; //append the text file content into textfile_data variable&nbsp; $textfile_data.= $line;}fclose($fh);//now textfile_data variable has the text file text$text_to_replace='Austin,12';//replace the text you want$new_textfile_data=str_replace("$text_to_replace",'',$textfile_data);//write the text file$fp = fopen("$textfile_name", 'w');if(fwrite($fp, "$new_textfile_data")){&nbsp; &nbsp; echo 'Replaced successfully';}fclose($fp);
随时随地看视频慕课网APP
我要回答