我需要用PHP的表单在txt文件中对句子的一部分进行一些修改



我真的需要你的帮助!提前为我的英语感到抱歉。。。

我需要用PHP文件编辑一个.txt文件,在txt文件中的修改需要来自一个表单,方法是"张贴";所以我的txt文件如下:

tour.name = something
image_foo = name of the image

我需要逐行读取txt文件,将每一行拆分为一个数组;并将其他阵列中的每一行拆分为tour.name<=数组键one/"="lt;=用"="/某物<=数组键二,我的代码需要检查数组键一是否==";tour.name";如果是";tour.name";将";某事";使用$_POST['tourname']。

在我的PHP文件中,我写道:

<form action="" method="post">
<label for="tourname">Titre:</label>
<input type="text" id="tourname" name="tourname"><br><br>
<input type="submit" value="Submit">
</form>
<?php
$myArray = array();
$file = fopen("file.txt", "r+");
while (!feof($file)) {
$line = fgets($file);
$myArray[] = explode(' = ', $line);
}
$arr_length = count($myArray);
$actualTitle = $myArray[0][1];
$modifiedTitle = $_POST['tourname'];
$modifiedTitle .= PHP_EOL;
for ($i=0; $i<$arr_length; $i++){
switch($myArray[0][0]){
case "tour.name":
$myArray[0][1] = str_replace($actualTitle, $modifiedTitle, $myArray[0][1]);
fseek($file, 12);
fwrite($file, $modifiedTitle);
break;
}
}
fclose($file);
?>

PS:我的代码需要不像我的代码那样精确:$myArray[0][0],因为代码需要是模块化的,txt文件可以更改,并且不能有相同的行数,也不能按相同的顺序。。。。代码需要检查句子的第一部分是否="0";tour.name";但是将来的锦标赛名称例如可以在线路30上。

如果有人能帮我,请!谢谢

如果我正确理解您只是想替换key=value对中key==tour.name的现有值,那么您可以极大地简化代码。我注意到你使用了一个switch表达式,这表明你的最终目标超出了你在问题中描述的范围,但下面的内容可以很容易地修改以适应。。。

<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['tourname'] ) ){
# assign POSTed value as variable for convenience
$tourname=$_POST['tourname'];

# always easier to use the full path
$file=__DIR__ .'/file.txt';

# read the file into an array - makes it easier to read, line by line
$lines=file( $file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );

#iterate through all lines
foreach( $lines as $i=> $line ){
# split the line by the delimiter `=`
list( $param, $value )=explode( '=', $line );

# basic comparison test
if( trim( $param ) == 'tour.name' ){
# find the position in the array where this current line occurs
$pos=array_search($line,$lines);

#generate new content using POSTed value
$line=sprintf('%s=%s',trim($param),trim($tourname));

#splice the new value into the original position
array_splice($lines,$pos,1,$line);
}
}
# save the text file
file_put_contents($file,implode(PHP_EOL,$lines));
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<title>edit textfile</title>
</head>
<body>
<form method='post'>
<input type='text' name='tourname' />
<input type='submit' />
</form>
</body>
</html>

最新更新