使用PHP替换文本文档中的特定字符串

时间:2018-09-08 15:39:54

标签: php html

我正在尝试使用户输入表单数据,然后单击“提交”时,它将表单数据放置在现有的文本文件中,并用该表单数据替换特定的字符串。

<?php
$myFile = "freewill.doc";
$fh = fopen($myFile, 'a') or die("can't open file");
$fName = $_POST["fName"];
fwrite($fh, $fName);
$mInitial = $_POST["mInitial"];
fwrite($fh, $mInitial);
$lName = $_POST["lName"];
fwrite($fh, $lName);
$placeholders = array('fin', 'min', 'lana');

$namevals = array($fName,$mInitial,$lName);

echo "<br/>namevals 0:".$namevals[0];

$path_to_file = 'freewill.doc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($placeholders,$namevals,$file_contents);

//build the string by putting each piece of text and variable exactly where 
you want it:
$string = "I, ".$fName." ".$mInitial." ".$lName.", a resident of Neverland 
County, Virginia, revoke any prior wills and amendments to wills made by me 
and declare this Will to be my Last Will and Testament.";

file_put_contents($path_to_file,$string);
fclose($fh);
?> 

这是我已经拥有的东西,但是它所做的全部都是通过代码构建字符串,而不是将其实际插入文件中,而是重写整行。当用户点击“提交”时,我需要转到另一个页面,因此数据需要传递,而不是替换已经完成的工作,而是继续添加到其中。

<h2>Please enter your name.</h2>
<form method="post" action="<?php echo 
htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
First Name: <input type="text" name="fName">
<br><br>
Middle Initial: <input type="text" name="mInitial">
<br><br>
Last Name: <input type="text" name="lName">
<br><br>
<input type="submit" name="submit" value="Next"> 
<button type="button" onclick="location.href='download.php'">Download 
will</button>  
</form>

这是我的表单数据

1 个答案:

答案 0 :(得分:0)

更改代码如下:

$file_contents = str_replace($placeholders,$namevals,$file_contents);

// removed $string

file_put_contents($path_to_file,$file_contents);
fclose($fh);

问题是您正在将$ string写入文件,而不是写入从文件中提取的$ file_contents。