So, I have a code that based on user's input write data to the file. Basically user select the date and the workout which on submit get written to the file. When I try to set it up to check if the string (date) already exist in the file I cannot make it work so that existing line is replaced.
Current code that is writing user's input to the file:
<?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");
?>
My attempts were with if statement but again I couldn't manage to write the code that will replace the line with if exists. This is what I have:
<?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");
?>
Currently it is doing this
08-04-2014 : Chest
08-05-2014 : Legs
08-04-2014 : Back
I want this
Now when user choose August 4th again that line to be replaced with new/same choice of workout depending what user selects.
08-04-2014 : Back
08-05-2014 : Legs
Can someone help with the part where I struggle to make this work. Thank you so much in advance.
As explained by Barmar in the comments:
$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
";
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));
So, you explode the file, go thru it, line by line, if found overwrite that line, if not append it to the end of the array, then glue it back together and put it back in the file.
You'll get the idea.
Hope it helps.