0

I have a Delete link in my profile page which links to "delete.php?snum=" . $snum. I have a $snum=$_GET['snum']; in delete.php. I have a file named "SLBrecords.csv" which looks like

12345 Barney
67890 Stinson

and I would like to create a script that would search for $snum in the file and delete the line that contains it. I think this is easy but I keep messing with implode, strpos, and other functions now but I'm still not able to make it work.

EDIT: Here is my code.

<?php

$snum=$_GET['snum'];

$filePath = './SLBrecords.csv';

$fileArr = file( $filePath );

foreach($fileArr as $line)
    if (strpos($line,$snum) !== false) {
        unset($line);
    }
$success = FALSE;
if ( file_put_contents( $filePath, implode( '', $fileArr ), LOCK_EX ) )
{
    $success = TRUE;
}

?>

Edit: How can I delete the line and also delete the newline that comes with it?

2
  • Why is this question tagged with "mysql"? Commented Apr 16, 2013 at 7:15
  • I am using Apache in this web application that's why it was in the tags earlier, but for some unknown reason somebody edited the tags and added "mysql" to it. Commented Apr 16, 2013 at 7:19

1 Answer 1

1

unset($line) is wrong. Try

foreach($fileArr as $k=>$line) {
    if (strpos($line,$snum) !== false) {
        unset($fileArr[$k]);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Sweet! It works like a charm. However, a newline is left from the deletion. Can I add anything to this code that does that?
I tried adding trim(preg_replace('/\s\s+/', ' ', $fileArr[$k])); after unset but it still doesn't work in some cases.
I think something wrong with csv file. Try this: $fileArr = file( $filePath, FILE_SKIP_EMPTY_LINES);
Nope, newline still there :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.