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.

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

报告相同问题?

悬赏问题

  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页