0

I need to delete a specific string set from a txt file. 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.

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. The data comes in as direct data from the file() read, so it should work. 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.

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"

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

<!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>
Knight_Art
  • 21
  • 4
  • to start: `!= $found` should be `!$found` in the `for` loop you mention. Currently it is a syntax error – Dan Nov 21 '17 at 16:34
  • Show us inputs and outputs. You have explained everything except the inputs and expected output of the function. What is `$fullNameAndEmail` – Andreas Nov 21 '17 at 16:36
  • Are you trying to reinvent str_replace? https://3v4l.org/gpTEg#vhhvm-3185 – Andreas Nov 21 '17 at 16:40
  • $fullNameAndEmail contains a ordered set, holding in order of "firstname lastname emailaddr" from the input from a user entered form. It stores this into a text file, which the entries are used here to be removed from, to remove a person from the guest book. @Andreas Also our professor won't let us use str_replace, that's why we have to do this complicated function set to do the equivalent. – Knight_Art Nov 21 '17 at 16:41
  • So you are trying to reinvent str_replace? See link above. And now you got downvoted for not being clear about it being an assignment with limitations. – Andreas Nov 21 '17 at 16:42
  • Sadly yes. Our professor wanted us to do it this way. For some reason. The professor would not let us use premade array sorting or search functions already built in to php, essentially making us reinvent the str_replace(), asort() and other functions. – Knight_Art Nov 21 '17 at 16:45
  • Also, it was bolded that there were limitations. And I quote "We were NOT allowed to use prebuilt sorting functions or use functions like str_replace or similar code" @Andreas – Knight_Art Nov 21 '17 at 16:46
  • Sorry, didn't see that. I will remove my dw. – Andreas Nov 21 '17 at 16:49

1 Answers1

0

I think you have overcomplicated it.
I foreach each line and check if it matches.
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.

$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

Andreas
  • 23,610
  • 6
  • 30
  • 62
  • Trying to test values in results in the contents of the file sadly being deleted.. I tried putting a string set from a file_get_contents outset to show the data to search. This was placed in $str = $variable, where $variable is where it's stored. Putting the complete string entered in ($fullNameAndEmail) into $find results in the entire contents of the text file to be removed... Do you have a solution to this? The contents of $arr are being put back into the file afterwards. – Knight_Art Nov 21 '17 at 17:39
  • To show what I mean: $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); – Knight_Art Nov 21 '17 at 17:40
  • You still have not showed us an input and expected output. It works for the data I supply it. If your data is that far off from mine **you have to show it**. Otherwise I (we) can't help you – Andreas Nov 21 '17 at 17:46
  • The expected output is almost identical to yours. I'll grab an example of input and write it on the main file. Will re-comment once it's edited in. – Knight_Art Nov 21 '17 at 17:49
  • Edit made. @Andreas – Knight_Art Nov 21 '17 at 17:55
  • I can't see what the problem is https://3v4l.org/v6cmt one thing from your edit is that you have undefined variables. $fisrtName and $lastName is not defined. But if I assume as linked it works as expected. And your code here in comments say `$rewrittenList = trim($arr)."\n";` where do you get that from? Trim()? What is that supposed to do? How are you trimming an array? You should be getting a array to string conversion error. You have errors on, right? – Andreas Nov 21 '17 at 18:23
  • In the current format it does. The data is pulled in correctly into the form, as it passes error checks. I was hesitant to post the full code but It appear I'll have to. Full Code going up now of what it's sitting at. – Knight_Art Nov 21 '17 at 18:27
  • Dear God! I understand why you was reluctant. But again, what is `trim($arr);` supposed to do? It's not something I gave you. It should give you an error. Here http://php.net/manual/en/function.trim.php see? `trim(string)` your code says `trim($arr)` and arr is short for array. Array != String – Andreas Nov 21 '17 at 18:36
  • Yes... It's a bit of a beast code wise. The code version you gave me passes the error checks in that version, Passing the testBool, Email check and filesize check (Checking if the file still has data), and the code runs through. However when I go to open the file, the file is empty. I'll try it without trim($arr) and perhaps that will help. Nevermind. The code doesn't print blank now, It just prints "Array" – Knight_Art Nov 21 '17 at 18:44
  • **YOU CAN NOT PRINT OR TRIM AN ARRAY**. Can you look the the code I have given you?! I have not written trim or echo array. I wrote implode! http://php.net/manual/en/function.implode.php read up on the basic stuff! All the functions you are trying to use wants **strings** not **arrays**! You must learn the basics or at least read the manual. – Andreas Nov 21 '17 at 18:52