[英]Replace multiple strings in PHP
我想替換我的docx文件中的多個單詞。 我使用了輸入元素中的單詞,然后將它們通過“ POST”方法傳遞。 我已經替換了'$ bedrijfsnaam',但是我想添加更多str替換。 我創建了“ $ newContents2”,但按照我的想法,它沒有用。 我該如何解決? 我是否需要添加另一個“ 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);
您將要繼續編輯相同的內容。
$newContents = str_replace('$bedrijfsnaam', $bedrijfsnaam, $oldContents);
第一次替換的結果在$newContents
,因此,如果您希望以此為基礎,則需要在$newContents
替換第二個字符串,並將結果存儲在$newContents
,該結果現在包含兩個字符串替換的結果。
$newContents = str_replace('$naam', $naam, $newContents);
編輯:更好的是,您可以只使用數組並在一行中完成所有操作
$newContent = str_replace(
['$bedrijfsnaam', '$naam'],
[ $bedrijfsnaam, $naam],
$oldContents
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.