简体   繁体   中英

Replace multiple strings in PHP

I want to replace multiple words in my docx-file. I used the words from the input-elements and I pass them through the 'POST'-method. I already replaced the '$bedrijfsnaam' but I want to add more str replacements. I created '$newContents2' but as I thought, it didn't work. How can I solve this? Do I have to add another 'oldContents' like '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 = 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
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM