所以,我有一个基于用户输入的代码写入文件的数据。基本上用户选择提交的日期和锻炼写入文件。当我尝试将其设置为检查文件中是否已存在字符串(日期)时,我无法使其工作以便替换现有行。
将用户输入写入文件的当前代码:
<?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
有人可以帮我解决这个问题。非常感谢你。
答案 0 :(得分:0)
正如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));
所以,你爆炸文件,一行一行,如果发现覆盖该行,如果没有将它附加到数组的末尾,然后将它粘合在一起并将其重新放回文件中。
你会明白这一点。
希望它有所帮助。