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.