【问题标题】:Php: Delete string from text file [duplicate]Php:从文本文件中删除字符串[重复]
【发布时间】:2017-11-21 16:28:54
【问题描述】:

我需要从一个 txt 文件中删除一个特定的字符串集。目前,代码以类似的方式将数据直接发布到文件中。但是,尝试删除以相同方式输入的相同数据是不允许的。在当前状态下,删除字符串的代码如下所示。

我们被不允许使用预构建的排序函数或使用 str_replace 或类似代码之类的函数。

这里是删除字符串的当前代码:

        $blankReplace = "";
        $found = false;
        $fileData = file($fileInput,FILE_IGNORE_NEW_LINES);
        for($i = 0; ($i < count($fileData)) && != $found; $i ++)
        {
            if($fullNameAndEmail == $fileData[$i])
            {
                $pos = $i;
                $name = $fileData[$i];
                $found = true;
            }
        }
        if($found == true)
        {
            // Exit path. Go to for($j = 0) path
            unset($fileData[$pos]);
            shuffle($fileData);
        }
        else
        {
            //Error Msg
        }
        $writeToFile = fopen($inputFile,'w+');
        for($j = 0;$j<count($fileData);$j++)
        {
               if(trim($fileData[$j]) != " ")
               {
                   $rewrittenList = trim($fileData[$j])."\n";
                   fwrite($writeToFile, $rewrittenList);


               }
        }

代码在研究错误后在代码中输出错误T_IS_NOT_EQUAL。数据作为来自 file() 读取的直接数据进来,所以它应该可以工作。该错误当前指向for($i = 0; ($i &lt; count($fileData)) &amp;&amp; != $found; $i ++) 行,但也可能引用了代码中的类似事件。

数据输入格式:

firstname lastname emailaddress

如果提到的名称出现多个实例,我还需要能够处理,所以说我们有:

Matt Person emailaddr@email.com
Matt Person emailaddr@email.com

在与此类似的情况下,它将删除一个实例,而不是全部。

感谢您的帮助,提前感谢您的时间。

编辑:

Example input:
Matthew person person@email.com
John holton person@email.com
Person Name person@gmail.com

用户将输入一个人的姓名(按上述格式),这将导致删除一个人。假设他们输入表单:

$fullName = "Matthew person";
$emailAddr = "person@email.com";
The output will edit the data to put the data into a single line again
$fullNameAndEmail = $firstName." ".$lastName." ".$emailAddr;

代码的输出,在本例中将删除“Matthew person person@email.com”

所以文本文件中的输出会输出:

John holton person@email.com
Person Name person@gmail.com

编辑 2:当前状态下的代码

<!doctype HTML>
<html>
<meta charset="utf-8">
<head>
<title>Updating the guest book!</title>
</head>

<body>
<?php


$fileInput = "guestBook.txt";
$fileInputInData = file_get_contents($fileInput);   // Gets data from file
$testBool = file_exists($fileInput);
$fullName = trim($_POST["fullName"]);
$emailAddr = trim($_POST["emailAddr"]);
$fileSize = filesize($fileInput);

if(!empty($fullName) and !empty($emailAddr))
{
    if($testBool == 0)
    {
        echo "There was an issue with the file. Please have it checked.</br>";
    }
    else
    {   
        echo "Made it into else path for testBool </br>";
        if($fileSize > 0)
        {   #code for truth
            echo "Made it into filesize check. Filesize: $fileSize </br>";


            $fullNameLen = strlen($fullName);
            $emailAddrLen = strlen($emailAddr);
            $fullNameArr = explode(" ", $fullName);
            $firstName = trim($fullNameArr[0]);
            $lastName = trim($fullNameArr[1]);
            $fullNameToWrite =$firstName." ".$lastName;
            $emailAddrCheck=substr_count($emailAddr, "@");
            if ($emailAddrCheck == 1) 
            {
                echo "Email address check passed</br>";
                #email addr entered right path
                $fullNameAndEmail =$fullNameToWrite." ".$emailAddr." has signed in.\n";
                $inputFile = "guestBook.txt";
                //$pos = strpos($writeToFile, $fullNameAndEmail);
                //$writeToFileEx = explode("\n", $fileInputInData);
                $blankReplace = "";
                $str = $fileInputInData;
                $find = $fullNameAndEmail;
                $arr=explode("\n", $str);
                Foreach($arr as $key => &$line)
                {
                    If($line == $find)
                    {
                        Unset($arr[$key]);
                        shuffle($arr);
                    }
                }
                $writeToFile = fopen($inputFile,'w+');
                $rewrittenList = trim($arr)."\n";
                fwrite($writeToFile, $rewrittenList);
                fclose($inputFile);
            }
            else            {
                echo "Email address check failed. Invalid email address entered. </br>
                        Line 55 occured.</br>";
                #email addr entered wrong message
            }
                //asort(array) sorts array low to high (ascending)
                //arsort(array) sorts array high to low (descending)

        }
        else
        {
            echo "Did not make it into filesize check. Filesize: $fileSize. Line 63 occured </br>";
        }
    }
}
else if (empty($fullName) or empty($emailAddr))
{
    echo "Error! Line 23: One of the inputs was left empty. Line 69 occured </br>";
}
else
{
    echo "Error! Line 23: Did not detect any values in either data area,</br>and program
     did not go into first error. Line 73 occured </br>";
}

?>
<br>
</body>
</html>

【问题讨论】:

  • 开始:!= $found 应该是您提到的for 循环中的!$found。目前是语法错误
  • 向我们展示输入和输出。除了函数的输入和预期输出之外,您已经解释了所有内容。什么是$fullNameAndEmail
  • 你想重新发明 str_replace 吗? 3v4l.org/gpTEg#vhhvm-3185
  • $fullNameAndEmail 包含一个有序集,按照用户输入表单的输入中的“firstname lastname emailaddr”的顺序保存。它将其存储到一个文本文件中,这里使用条目从中删除,以从留言簿中删除一个人。 @Andreas 另外,我们的教授不会让我们使用 str_replace,这就是为什么我们必须做这个复杂的函数集来做同样的事情。
  • 所以你想重新发明str_replace?见上面的链接。现在你因为不清楚这是一项有限制的任务而被否决了。

标签: php string file


【解决方案1】:

我认为你把它复杂化了。
我 foreach 每一行并检查它是否匹配。
如果是这样,我会取消设置该行。

循环结束后,我在新行内爆,字符串恢复正常,但没有 $find's。

$str = "Matt Person emailaddr@email.com
John doe doesoe@gmail
Matt Person emailaddr@email.com
Trump donald@whitehouse";

$find = "Matt Person emailaddr@email.com";

$arr=explode("\n", $str);

Foreach($arr as $key => &$line){

    If($line == $find){
        Unset($arr[$key]);
    }
}
Echo implode("\n", $arr);

https://3v4l.org/hmSr7

【讨论】:

  • 尝试测试值导致文件内容不幸被删除。我尝试从 file_get_contents 开始放置一个字符串集以显示要搜索的数据。这被放置在 $str = $variable 中,其中 $variable 是它的存储位置。将 ($fullNameAndEmail) 中输入的完整字符串放入 $find 会导致文本文件的全部内容被删除......你有解决方案吗?之后 $arr 的内容将被放回文件中。
  • 显示我的意思: $str = $fileInputInData; $find = $fullNameAndEmail; $arr=explode("\n", $str); Foreach($arr as $key => &$line) { If($line == $find) { Unset($arr[$key]);洗牌($arr); } } $writeToFile = fopen($inputFile,'w+'); $rewrittenList = trim($arr)."\n"; fwrite($writeToFile, $rewrittenList);
  • 您还没有向我们展示输入和预期输出。它适用于我提供的数据。如果您的数据与我的数据相差那么远您必须显示它。否则我(我们)帮不了你
  • 预期输出与您的几乎相同。我将获取一个输入示例并将其写入主文件。编辑完成后会重新评论。
  • 已编辑。 @安德烈亚斯
猜你喜欢
  • 1970-01-01
  • 2016-12-05
  • 1970-01-01
  • 2016-07-13
  • 2014-12-19
  • 1970-01-01
  • 1970-01-01
  • 2012-04-06
相关资源
最近更新 更多