替换PHP中的多个字符串
我想替换docx文件中的多个单词。我使用输入元素中的单词,并通过“POST”方法传递它们。我已经替换了“$bedrijfsnaam”,但我想添加更多str替换。我创建了“$newContents2”,但正如我所想,它不起作用。我怎样才能解决这个问题?我是否必须添加另一个“oldContents”,如“oldContents2”替换PHP中的多个字符串,php,Php,我想替换docx文件中的多个单词。我使用输入元素中的单词,并通过“POST”方法传递它们。我已经替换了“$bedrijfsnaam”,但我想添加更多str替换。我创建了“$newContents2”,但正如我所想,它不起作用。我怎样才能解决这个问题?我是否必须添加另一个“oldContents”,如“oldContents2” $bedrijfsnaam = $_POST['bedrijfsnaam']; $offertenummer = $_POST['offertenummer']; $na
$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);
您将希望继续编辑相同的内容
$newContents = str_replace('$bedrijfsnaam', $bedrijfsnaam, $oldContents);
第一次替换的结果在$newContents
中,因此,如果要在此基础上进行构建,则需要替换$newContents
中的第二个字符串,并将结果存储在$newContents
中,该字符串现在包含两次替换的结果
$newContents = str_replace('$naam', $naam, $newContents);
编辑:更好的是,您可以只使用数组并在一行中完成所有操作
$newContent = str_replace(
['$bedrijfsnaam', '$naam'],
[ $bedrijfsnaam, $naam],
$oldContents
);
“$bedrijfsnaam”
是文本值,不引用变量。您可以使用数组进行搜索和替换值,请参阅手册()。另外,请注意双引号字符串中的美元符号-php将尝试解析变量并用变量()替换文本