简体   繁体   English

PHP:从文本文件中删除字符串

[英]Php: Delete string from text file

I need to delete a specific string set from a txt file. 我需要从txt文件中删除特定的字符串集。 Currently, the code works in a similar manner to post the data directly to the file. 当前,代码以类似的方式工作以将数据直接发布到文件中。 However, trying to remove the same data, inputted in the same manner, will not allow it. 但是,尝试删除以相同方式输入的相同数据将不允许这样做。 In it's current state, the code looks like this for the string removal. 在当前状态下,用于删除字符串的代码如下所示。

We were NOT allowed to use prebuilt sorting functions or use functions like str_replace or similar code. 我们不允许使用预排序功能使用功能,如str_replace函数或类似代码。

Here is the current code for the string removal: 这是删除字符串的当前代码:

        $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);


               }
        }

The code outputs an error of T_IS_NOT_EQUAL in code upon researching the error. 研究错误后,代码会在代码中输出错误T_IS_NOT_EQUAL The data comes in as direct data from the file() read, so it should work. 数据作为从file()读取的直接数据输入,因此它应该可以工作。 The error is pointing at for($i = 0; ($i < count($fileData)) && != $found; $i ++) line currently, but likely also references a similar occurrence in the code. 该错误当前指向for($i = 0; ($i < count($fileData)) && != $found; $i ++)行,但也可能在代码中引用了类似的情况。

The data is inputted in the format: 数据以以下格式输入:

firstname lastname emailaddress

I also need to be able to handle if multiple instances of the mentioned name occur so say we have: 我还需要能够处理上述名称的多个实例,所以我们有:

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

That it will delete one instance, and not all, in cases similar to this. 在类似情况下,它将删除一个实例,而不是全部实例。

Any help is appreciated, Thank you for your time in advance. 感谢您的帮助,谢谢您的宝贵时间。

EDIT: 编辑:

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

The user will input a person's name (in format above) and it will result in removing a person. 用户将输入一个人的名字(上面的格式),这将导致一个人的删除。 Say they input into the form: 说他们输入表格:

$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;

The output of the code, in this example will remove "Matthew person person@email.com" 代码的输出,在此示例中,将删除“ Matthew person person@email.com”

So the output in the text file will output: 因此,文本文件中的输出将输出:

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

Edit 2: Code in it's current state 编辑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>

I think you have overcomplicated it. 我认为您过于复杂了。
I foreach each line and check if it matches. 我foreach每一行,并检查是否匹配。
If it does I unset the line. 如果可以,我取消设置线路。

After the loop I implode on new line and the string is back to normal but without the $find's. 循环后,我在新行上爆裂,字符串恢复正常,但没有$ find的字符串。

$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 https://3v4l.org/hmSr7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM