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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?