繁体   English   中英

在PHP中替换多个字符串

[英]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.

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