在文件中搜索一个元素数组,并用另一个元素阵列php替换它们



我正在尝试

  1. 打开并读取文件
  2. 在文件中搜索几个单词
  3. 将这些单词替换为其他单词
  4. 将内容重新放入文件中

用于搜索和替换的单词是从用户输入框中动态获取的。这是我要使用的代码,

$filename = 'test1.txt'; 
($handle = fopen($filename, 'r+')) or die(); 
$content = fread($handle, filesize($filename));
echo $content.'<br>'.'<br>';
if (isset($_POST['findtext']) && isset($_POST['replacetext'])) {
$findtext = $_POST['findtext'];
$replacetext = $_POST['replacetext'];
if (!empty($findtext) && !empty('$replacetext')) {
$ftxtarray = explode( ',', strtolower($findtext));
$rtxtarray = explode(',', strtolower($replacetext));
//  code?
echo $content;
} else {
echo 'Please type in "Replace:" words and "Replace with:" words..';
}
}

HTML、

<form action="firstfile.php" method="POST">
<br>Replace:<br>
<input type="text" name="findtext"><br>
Replace with:<br>
<input type="text" name="replacetext"><br>
<input type="submit" value="Submit">

假设"test1.txt"包含几个单词,包括"John Doe"one_answers"替换为:"字段中的"John,Doe"中的用户类型,以及"替换为"字段中"Richard,Roe"。我应该使用哪种方法来替换指定的单词?

使用str_replace(),放入要查找的单词的第一个参数数组,放入与第一个长度完全相同的第二个参数数组中,放入加载到变量中的文件的第三个内容中,就可以开始了。

相关内容

最新更新