如果存在PHP,如何替换文件中的行


How to replace line in the file if exists PHP

所以,我有一个代码,根据用户的输入写入数据到文件。基本上用户选择的日期和锻炼,在提交得到写入文件。当我试图设置它来检查字符串(日期)是否已经存在于文件中时,我无法使它工作,因此现有的行被替换。

将用户输入写入文件的当前代码:

<?php
   include 'index.php';
   $pickdate = $_POST['date'];
   $workout = $_POST['workout'];
   $date = '   '''.$pickdate .''' : ''<a href="../routines/'.$workout.'" target="_blank"><span>'.basename($workout,'.txt').'</span></a>'',' .PHP_EOL;
   $file = 'test.js';
   // Open the file to get existing content
   $current = file_get_contents($file);
   // Append a new workout to the file
   $current .= $date;
   $current = preg_replace('/};/', "", $current);
   $current = $current.'};';
   // Write the contents back to the file
   file_put_contents($file, $current);
   header("location:index.php");
?>

我的尝试是与if语句,但再次我无法设法编写代码,将替换行与if存在。这是我的文件:

<?php
   include 'index.php';
   $pickdate = $_POST['date'];
   $workout = $_POST['workout'];
   $date = '   '''.$pickdate .''' : ''<a href="../routines/'.$workout.'" target="_blank"><span>'.basename($workout,'.txt').'</span></a>'',' .PHP_EOL;
   $file = 'test.js';
   // Open the file to get existing content
   $current = file_get_contents($file);
   if (strpos($current, '   '''.$pickdate .'''') ) {
     #here is where I struggle#
   }
   else {
    // Append a new workout to the file
   $current .= $date;
   $current = preg_replace('/};/', "", $current);
   $current = $current.'};';
   // Write the contents back to the file
   file_put_contents($file, $current);
   }
  header("location:index.php");
?>

目前是这样

08-04-2014 : Chest
08-05-2014 : Legs
08-04-2014 : Back

我想要这个

现在,当用户再次选择8月4日时,这一行将被替换为新的/相同的锻炼选择,这取决于用户选择什么。

08-04-2014 : Back
08-05-2014 : Legs

有人可以帮助我努力使这个工作的部分。非常感谢。

正如Barmar在评论中解释的那样:

$current = trim(file_get_contents($file));
$current_lines = explode(PHP_EOL, $current);
/* saved already */
$saved = false;
foreach($current_lines as $line_num => $line) {
    /* either regex or explode, we explode easier on the brain xD */
    list($date_line, $workout_line) = explode(' : ', $line);
    echo "$date_line -> $workout_line 'n";
    if($date == $date_line) {
        /* rewrite */
        $current_lines[$line_num] = "$date : $workout";
        $saved = true;
        /* end loop */
        break;
    }        
}
/* append to the end */
if(!$saved) {
    $current_lines[] = "$date : $workout";
}
file_put_contents($file, implode(PHP_EOL, $current_lines));

你打开文件,逐行浏览它,如果找到,覆盖那行,如果没有,将它附加到数组的末尾,然后将它粘合在一起,并将其放回文件中。

你会明白的。

希望能有所帮助。