PHP-如何找到特定的单词并将其更改为另一个单词

时间:2018-10-05 23:17:13

标签: php

是否可以从文本文件中找到一个特定的单词并替换它,而无需实际删除PHP中的.txt文件的内容?我尝试了下面的代码,它只是添加到文本文件中。

<?php

$fileLocation = "$light_txt";

// Opens up the .txt file for writing and replaces any previous content
$fh = fopen($fileLocation, "a") or die("Something went wrong!");

// Write either 1 or 0 depending on request from index.html
$stringToWrite = "$onoroff \n";

// Writes it to the .txt file
fwrite($fh, $stringToWrite);
fclose($fh);

“ light.txt”中包含以下内容,

"L1
 L0 
 F"

如何将L0交换为L1,这样light.txt文件的内容将为“ L0,F”?谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

是的,您可以使用php file_get_content函数来实现,该函数将给定文件的内容作为字符串返回

test.txt文件包含

  

John Doe,你好

// Get all the content of the file
$content = file_get_contents('test.txt'); 
// Replace "John Doe" with "Jeanne Doe"
$contentReplace = str_replace('John Doe', 'Jeanne Doe', $content);
// Open the file in writing mode
$file = fopen('test.txt', 'w');
// Replace the content of the `test.txt` by the new content generated
fwrite($file, $contentReplace);

test.txt文件的内容现在是

  

你好珍妮·杜(Jeanne Doe)