【问题标题】:Find and replace word in text file在文本文件中查找和替换单词
【发布时间】:2013-11-18 12:22:49
【问题描述】:

我想检测文本文件中的单词是否存在,然后将其删除。所以,这是我的代码:

<?php
$search = $id;
$lines = file("./user/".$_GET['own'].".txt");
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
if(strpos($line, $search) !== false)
{
$found = true;
// open to read and modify
$file = "./user/".$_GET['own'].".txt";
$fh = fopen($file, 'r+');
$data = fread($fh, filesize($file));
$new_data = str_replace($id."\n", "", $data);
fclose($fh);
// Open to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_data);
fclose($fh);
$status = "has been successfully deleted.";
}
}
// If the text was not found, show a message
if(!$found)
{
 $status = "is not exist in your list.";
}
?>

我在几个小时前就得到了这个工作。我对我的脚本做了一些更改,但不知何故,它不再工作了。任何人都可以看穿代码并告诉我出了什么问题吗??

或者任何人都可以提供更简单的方法来做我想做的事吗?我的代码乱七八糟..

【问题讨论】:

    标签: php


    【解决方案1】:

    我想检测一个文本文件中的单词是否存在,然后删除它..

    <?php
     $search = $id;
     $filename="./user/".$_GET['own'].".txt";
     $contents = file_get_contents($filename);
     $contents = str_replace($id."\n", "", $contents);
     file_put_contents($filename,$contents);
    ?>
    

    仅此而已。

    编辑:

    为了使这与您的解决方案等效,可以使用

    <?php
     $search = $id;
     $filename="./user/".$_GET['own'].".txt";
     $contents = file_get_contents($filename);
     $contents = str_replace($id."\n", "", $contents,$count);
     if($count>0)
     {
      file_put_contents($filename,$contents);
      echo "found and removed";
     }
     else
     {
      echo "not found";
     }
    ?>
    

    【讨论】:

    • 仅此而已???? -_- 当我的代码比你的长三倍时,多么可耻。顺便说一句,我会在一分钟内测试它
    • 是的,仅此而已,这里唯一缺少的是您的条件echo
    • 再一次你的代码比我好.. 谢谢兄弟.. 你是最好的.. 我用 1/2 小时编写了混乱的代码,你在几分钟内编写了更清晰的代码.. :)
    猜你喜欢
    • 1970-01-01
    • 2011-04-25
    • 2017-11-18
    • 2015-07-07
    • 2017-11-04
    • 2020-07-29
    • 1970-01-01
    • 2022-11-19
    • 2013-05-26
    相关资源
    最近更新 更多