在PHP中,你可以使用file()函数来读取文件内容,然后使用str_replace()函数来替换文件中的特定内容。以下是一个示例:
<?php // 读取文件内容 $file = file("example.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); // 要替换的内容 $search = "old_text"; $replace = "new_text"; // 使用 str_replace() 函数替换内容 $new_content = str_replace($search, $replace, implode("", $file)); // 将替换后的内容写回文件 file_put_contents("example.txt", $new_content); echo "文件内容已成功替换!"; ?> 在这个示例中,我们首先使用file()函数读取example.txt文件的内容。然后,我们使用str_replace()函数将old_text替换为new_text。最后,我们使用file_put_contents()函数将替换后的内容写回文件。