2017-07-06 234 views
0

我想替換我的docx文件中的多個單詞。我使用了input-elements中的單詞,並通過'POST'方法傳遞它們。我已經替換了'$ bedrijfsnaam',但我想添加更多的str替換。我創建了'$ newContents2',但正如我想的那樣,它不起作用。我該如何解決這個問題?我是否必須添加另一個'oldContents',如'oldContents2'?在PHP中替換多個字符串

$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); 
+1

''$ bedrijfsnaam''是字面值,不引用變量。您可以使用數組進行搜索並替換值,請參閱手冊(http://php.net/manual/en/function.str-replace.php)。 – chris85

+0

還要注意雙引號字符串中的美元符號-php將嘗試解析變量並用變量替換文本(http://php.net/manual/en/language.types.string.php#language .types.string.parsing) – reafle

回答

1

您將要繼續編輯相同的內容。

$newContents = str_replace('$bedrijfsnaam', $bedrijfsnaam, $oldContents); 

第一置換的結果是$newContents,所以如果你想建立在這一點,你需要更換第二個字符串中$newContents,並把結果保存在$newContents,它現在包含兩個字符串的結果更換。

$newContents = str_replace('$naam', $naam, $newContents); 

編輯:更重要的是,你可以只使用數組和做這一切在同一行

$newContent = str_replace(
    ['$bedrijfsnaam', '$naam'], 
    [ $bedrijfsnaam, $naam], 
    $oldContents 
);