[英]Replace multiple strings in PHP
I want to replace multiple words in my docx-file. 我想替换我的docx文件中的多个单词。 I used the words from the input-elements and I pass them through the 'POST'-method.
我使用了输入元素中的单词,然后将它们通过“ POST”方法传递。 I already replaced the '$bedrijfsnaam' but I want to add more str replacements.
我已经替换了'$ bedrijfsnaam',但是我想添加更多str替换。 I created '$newContents2' but as I thought, it didn't work.
我创建了“ $ newContents2”,但按照我的想法,它没有用。 How can I solve this?
我该如何解决? Do I have to add another 'oldContents' like 'oldContents2'?
我是否需要添加另一个“ oldContents”,例如“ oldContents2”?
$bedrijfsnaam = $_POST['bedrijfsnaam'];
$offertenummer = $_POST['offertenummer'];
$naam = $_POST['naam'];
$zip = new ZipArchive;
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
$wordDoc = "Document.docx";
$newFile = $offertenummer . ".docx";
copy("Document.docx", $newFile);
if ($zip->open($newFile) === TRUE) {
$oldContents = $zip->getFromName($fileToModify);
$newContents = str_replace('$bedrijfsnaam', $bedrijfsnaam, $oldContents);
$newContents2 = str_replace('$naam', $naam, $oldContents);
$zip->deleteName($fileToModify);
$zip->addFromString($fileToModify, $newContents);
$return =$zip->close();
If ($return==TRUE){
echo "Success!";
}
} else {
echo 'failed';
}
$newFilePath = 'offerte/' . $newFile;
$fileMoved = rename($newFile, $newFilePath);
You're going to want to keep editing the same content. 您将要继续编辑相同的内容。
$newContents = str_replace('$bedrijfsnaam', $bedrijfsnaam, $oldContents);
The result of the first replacement is in $newContents
, so if you want to build upon that, you need to replace the second string in $newContents
and store the result in $newContents
, which now contains the result of both string replacements. 第一次替换的结果在
$newContents
,因此,如果您希望以此为基础,则需要在$newContents
替换第二个字符串,并将结果存储在$newContents
,该结果现在包含两个字符串替换的结果。
$newContents = str_replace('$naam', $naam, $newContents);
Edit: Better yet, you can just use arrays and do it all in one line 编辑:更好的是,您可以只使用数组并在一行中完成所有操作
$newContent = str_replace(
['$bedrijfsnaam', '$naam'],
[ $bedrijfsnaam, $naam],
$oldContents
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.