Php удаление выбранной строки

How to delete a line from the file with php?

I have a file named $dir and a string named $line , I know that this string is a complete line of that file but I don’t know its line number and I want to remove it from file, what should I do? Is it possible to use awk?

10 Answers 10

$contents = file_get_contents($dir); $contents = str_replace($line, '', $contents); file_put_contents($dir, $contents); 

i tried that code writing echo between each line, its fine until file_put_contents function, i dont understand why it doesnt work:S

@ibrahim — What do you mean didn’t work? Could you get all the contents through file_get_contents . Tell me exactly which part didn’t work.

@Amir Some times line brakes are made differently, I’ve just tasted my solution and it worked as expected. Anyway, try $contents = str_replace($line.PHP_EOL, », $contents); instead

Read the lines one by one, and write all but the matching line to another file. Then replace the original file.

this will just look over every line and if it not what you want to delete, it gets pushed to an array that will get written back to the file. see this

 $DELETE = "the_line_you_want_to_delete"; $data = file("./foo.txt"); $out = array(); foreach($data as $line) < if(trim($line) != $DELETE) < $out[] = $line; >> $fp = fopen("./foo.txt", "w+"); flock($fp, LOCK_EX); foreach($out as $line) < fwrite($fp, $line); >flock($fp, LOCK_UN); fclose($fp); 

For simplicity why not build the $out as a string rather than an array and then use file_put_contents with LOCK_EX? Any reason for this approach?

Читайте также:  Язык html или php

It can be solved without the use of awk:

function remove_line($file, $remove) < $lines = file($file, FILE_IGNORE_NEW_LINES); foreach($lines as $key =>$line) < if($line === $remove) unset($lines[$key]); >$data = implode(PHP_EOL, $lines); file_put_contents($file, $data); > 

@Michael, The SO is asking two question! 1)what should I do? 2)Is it possible to use awk?, so I did answer to question one. and also see the best answer marked, it didn’t use awk .

Another approach is to read the file line by line until you find a match, then truncate the file to that point, and then append the rest of the lines.

. ionno, put them into memory and then truncate..long as the file isn’t too big. not saying it’s a better solution.. should result in fewer disk writes though.

This is also good if you’re looking for a substring (ID) in a line and want to replace the old line with the a new line.

$contents = file_get_contents($dir); $new_contents = ""; if (strpos($contents, $id) !== false) < // if file contains ID $contents_array = explode(PHP_EOL, $contents); foreach ($contents_array as &$record) < // for each line if (strpos($record, $id) !== false) < // if we have found the correct line continue; // we've found the line to delete - so don't add it to the new contents. >else < $new_contents .= $record . "\r"; // not the correct line, so we keep it >> file_put_contents($dir, $new_contents); // save the records to the file echo json_encode("Successfully updated record!"); > else

Running the code will change file to:

There is no reason, aside from readability perhaps. This was written 5 years ago while I was still a junior dev

Cool. When you have time, please update this post (that people are learning coding from) to reflect the best of your current dev knowledge. Also, modifying $record by reference seems unnecessary too.

@mickmackusa I don’t use PHP anymore, so I am not going to bother, as it would involve rewriting and testing. It is well commented so people learning can follow along. If people want a better answer they can use Naveed Ahmad’s answer.

All answeres here have in common, that they load the complete file into the memory. Here is an implementation of removing one (or more) line(s) without coyping the files content into a variable.

The idea is to iterate over the files lines. If a line should be removed, the lines length is added to the $byte_offset . The next line is then moved $byte_offset bytes «upwards». This is done with all following lines. If all lines are processed, the files last $byte_offset bytes are removed.

I guess that this is faster for bigger files because nothing is copied. And I guess that at some file size the other answers do not work at all while this one should. But I didn’t test it.

$file = fopen("path/to/file", "a+"); // remove lines 1 and 2 and the line containing only "line" fremove_line($file, 1, 2, "line"); fclose($file); 

The code of the fremove_line() function:

/** * Remove the `$lines` by either their line number (as an int) or their content * (without trailing new-lines). * * Example: * ```php * $file = fopen("path/to/file", "a+"); // must be opened writable * // remove lines 1 and 2 and the line containing only "line" * fremove_line($file, 1, 2, "line"); * fclose($file); * ``` * * @param resource $file The file resource opened by `fopen()` * @param int|string . $lines The one-based line number(s) or the full line * string(s) to remove, if the line does not exist, it is ignored * * @return boolean True on success, false on failure */ function fremove_line($file, ..$lines): bool < // set the pointer to the start of the file if(!rewind($file))< return false; >// get the stat for the full size to truncate the file later on $stat = fstat($file); if(!$stat) < return false; >$current_line = 1; // change to 0 for zero-based $lines $byte_offset = 0; while(($line = fgets($file)) !== false) < // the bytes of the lines ("number of ASCII chars") $line_bytes = strlen($line); if($byte_offset >0) < // move lines upwards // go back the `$byte_offset` fseek($file, -1 * ($byte_offset + $line_bytes), SEEK_CUR); // move the line upwards, until the `$byte_offset` is reached if(!fwrite($file, $line))< return false; >// set the file pointer to the current line again, `fwrite()` added `$line_bytes` // already fseek($file, $byte_offset, SEEK_CUR); > // remove trailing line endings for comparing $line_content = preg_replace("~[\n\r]+$~", "", $line); if(in_array($current_line, $lines, true) || in_array($line_content, $lines, true)) < // the `$current_line` should be removed so save to skip the number of bytes $byte_offset += $line_bytes; >// keep track of the current line $current_line++; > // remove the end of the file return ftruncate($file, $stat["size"] - $byte_offset); > 

Convert text to array, remove first line and reconvert to text

$line=explode("\r\n",$text); unset($line[0]); $text=implode("\r\n",$line); 

I think the best way to work with files is to act them like strings:

/** * Removes the first found line inside the given file. * * @param string $line The line content to be searched. * @param string $filePath Path of the file to be edited. * @param bool $removeOnlyFirstMatch Whether to remove only the first match or * the whole matches. * @return bool If any matches found (and removed) or not. * * @throw \RuntimeException If the file is empty. * @throw \RuntimeException When the file cannot be updated. */ function removeLineFromFile( string $line, string $filePath, bool $removeOnlyFirstMatch = true ): bool < // You can wrap it inside a try-catch block $file = new \SplFileObject($filePath, "r"); // Checks whether the file size is not zero $fileSize = $file->getSize(); if ($fileSize !== 0) < // Read the whole file $fileContent = $file->fread($fileSize); > else < // File is empty throw new \RuntimeException("File '$filePath' is empty"); >// Free file resources $file = null; // Divide file content into its lines $fileLineByLine = explode(PHP_EOL, $fileContent); $found = false; foreach ($fileLineByLine as $lineNumber => $thisLine) < if ($thisLine === $line) < $found = true; unset($fileLineByLine[$lineNumber]); if ($removeOnlyFirstMatch) < break; >> > // We don't need to update file either if the line not found if (!$found) < return false; >// Join lines together $newFileContent = implode(PHP_EOL, $fileLineByLine); // Finally, update the file $file = new \SplFileObject($filePath, "w"); if ($file->fwrite($newFileContent) !== strlen($newFileContent)) < throw new \RuntimeException("Could not update the file '$filePath'"); >return true; > 

Here is a brief description of what is being done: Get the whole file content, split the content into its lines (i.e. as an array), find the match(es) and remove them, join all lines together, and save the result back to the file (only if any changes happened).

// $dir is your filename, as you mentioned removeLineFromFile($line, $dir); 
  • You can use fopen() family functions instead of SplFileObject , but I do recommend the object form, as it’s exception-based, more robust and more efficient (in this case at least).
  • It’s safe to unset() an element of an array being iterated using foreach (There’s a comment here showing it can lead unexpected results, but it’s totally wrong: As you can see in the example code, $value is copied (i.e. it’s not a reference), and removing an array element does not affect it).
  • $line should not have new line characters like \n , otherwise, you may perform lots of redundant searches.
  • Don’t use

$fileLineByLine[$lineNumber] = ""; // Or even $fileLineByLine[$lineNumber] = null; 

Источник

Delete selected row from table in php

I am using the code (pasted below) to delete the record from the table when it’s selected by the checkbox . It is working, but it is not deleting the record from the table, it is only showing the echo «Records deleted Successfully.». Please have a look at my code and suggest me some changes.

@Mihai Iorga: yes, i am new for php and previous code was difficult to me for to learn so i try this code its eassy but not working pls explain me

8 Answers 8

Add error_reporting(E_ALL); to the top of your file. Now you will be able to see all errors. http://php.net/manual/en/function.error-reporting.php

Also, use var_dump() to check what is actually in your variables. When you run var_dump($_POST); you can clearly see what is actually in your post. http://php.net/manual/en/function.var-dump.php

if(isset($_POST['delete'])) < $delete = false; $ids = array(); foreach($_POST['checkbox'] as $val)< $ids[] = (int) $val; >$ids = implode("','", $ids); $sql = "DELETE FROM `test` WHERE id IN ('".$ids."')"; $delete = mysql_query($sql); $id = mysql_affected_rows(); if($delete) < echo $id." Records deleted Successfully."; >> 

also your check-boxes should have:

Put the delete code before selecting the records, then only you can see the actual records available in the DB.

there is no $rows here remove the s put

You should name the checkboxes something like

And then when you’re trying to delete

foreach ($_POST['checkbox'] as $id => $delete) < // delete id >

Your way of selecting an id by count is rather awkward, you’re also only deleting 1 row, which is apparently non-existant because the count is not an id. Also, the value of a checkbox is meant to be an indicator off the checkbox being ticked or not, it’s not usually holding a value, the usual way is to make the name hold what the checkbox actually means.

Источник

Php удаление выбранной строки

Почитал, что пишут на эту тему в «интернетах» — прикольно. смайлы .

Что нужно для удаления строки в php?

Для того, чтобы удалить уникальную строку в php надо соблюсти одно главное условие:

Если вы хотите удалить определенную, конкретную, уникальную строку в php вам потребуется какой-то уникальный идентификатор строки, по которому php мог найти эту строку!

Если речь идет о файле php(либо о коде php), то в файле php можно закомментировать строку и написать в этой строке все, что угодно:

Если это обычная строка(тип) — в смысле, что это текст, то здесь один единственный способ — разделение в массив, удаление строки по номеру ячейки.

Удаляем строку в php в тексте.

Для того, чтобы удалить строку в тексте вс помощью php, вам понадобится:

Нам нужен пример текста для удаления строки, поместим его в переменную:

$delete_string_php =’Здесь строка.

В котором требуется удалить строку.’;

Далее — вам потребуется функция explode. Применим её к данному тексту, разделителем будет перевод строки «\n»:

Вы получите массив, выведем с помощью print_r:

Обращаю ваше внимание на то, что нумерация строк начинается с нуля:

[2] => В котором требуется удалить строку.

Далее — например вам требуется удалить строку №1, вам потребуется unset применим её к массиву, и у вас получится:

[2] => В котором требуется удалить строку.

Теперь нужно массив вернуть в строку с помощью (implode).

Соберем весь код удаления строки в одно целое:

Код удаления строки в сборе

Код в сборе для удаления строки из переменной с текстом вы можете скачать здесь.

Удаляем строку в файле.

Алгоритм удаления строки аналогичный, что уже был описан в выше расположенном пункте с некоторыми отличиями.

Для того, чтобы удалить строку из файла вам понадобится:

Создадим первый файл — .txt — в котором будет находиться текст.

Получаем текст в переменную с помощью file_get_contents.

Далее вся теория из предыдущего пункта:

И далее готовую строку можем записать в старый файл, но поскольку — у нас тут задача стоит в том, чтобы показать пример. запишем текст в новый файл.

Соберем весь код удаления строки из файла.

Источник

Оцените статью