drf65218 2018-08-06 00:03
浏览 89
已采纳

搜索文件中的元素数组,并将其替换为另一个元素数组-php

I am trying to

  1. open and read a file,
  2. Search a few words within the file,
  3. Replace these words with some other words,
  4. Put content into the file again.

The words for search and replace are taken dynamically from user input boxes. Here's the code I am going with,

$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..';
    }

}

And the 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">

Lets say "test1.txt" contains few words including "John Doe" and user types in "John,Doe" in the "Replace:" field and "Richard,Roe" in the "Replace with:" field. Which method should I use to replace the specified words?

  • 写回答

1条回答 默认 最新

  • dqingn8836 2018-08-06 02:08
    关注

    Use str_replace() and put in first parameter array of words to find, in second parameter array with the exact length as the first one, in third contents of a file loaded into variable, and you're good to go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效