drf65218 2018-08-05 16: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-05 18: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部