2017-07-06 239 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 
);