There is a code that looks for a number in the file, and deletes it if it is present, and if not, it does nothing:

$key = $_REQUEST['del']; $filename = 'list.txt'; $lines = file($filename); $output = ''; foreach ($lines as $line) { if (!strstr($line, $key)) { $output .= $line; } } file_put_contents($filename, $output); 

But problems arise when the number 11 or 15 is allowed in the file and when you try to delete the number 1, which is not there, both 11 and 15 are deleted (that is, everything starts with 1). How to make so that only exact number was deleted? Tried to change strstr to preg_match, did not work ...

  • Yes, I already guessed, I just always came across most of the questions in English, so I thought that there was only English communication here - Denis
  • There are just a few different forums - Bookin
  • Already translated, thanks - Denis
  • you need a file in rows, then why bother? - teran

2 answers 2

Something like - (?:\D|^)(1)(?:\D|$) (what came first), find 1 if there are no numbers around.

Example

 $key = 1; $lines = ['asda asdf sdfasdas 11 adsdsdf', 'фыавыва ывавва 1 ыпвап ываыв 1']; $output = ''; foreach ($lines as $line) { if (!preg_match("/(?:\D|^)($key)(?:\D|$)/", $line)) { $output .= $line; } } echo $output; 
  • if (! preg_match ("/ (?: \ D | ^) $ line (?: \ D | $) /", $ key)) - did not work - Denis
  • you're confused with variable places - Bookin
  • Thanks, earned! - Denis

Read the entire file, why do you need it in lines?

 $txt = file_get_contents("list.txt"); $value = 15; // число для удаления $txt = preg_replace("/\b($value)\b/", "", $txt); file_put_contents("list.txt", $txt) 

However, it makes no sense to write the contents of the file back, if no match was found. Therefore you can:

  1. or pre-check the matches, and if they are available to carry out the replacement and save to a file.
  2. Either the second option is to perform a replacement, and check the length of the lines before and after the replacement, if not the same, then write it down.

also remember that you must validate the input data before you substitute it into a regular expression. That is, if you want to remove a number, then make sure that the number is transmitted. In other cases, escape the values ​​with preg_escape .