【问题标题】:Replace multiple strings in PHP替换PHP中的多个字符串
【发布时间】:2017-12-10 23:11:24
【问题描述】:

我想替换我的 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);

【问题讨论】:

标签: php


【解决方案1】:

你会想要继续编辑相同的内容。

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

第一次替换的结果在$newContents,所以如果你想以此为基础,你需要替换$newContents中的第二个字符串并将结果存储在$newContents中,现在包含的结果两个字符串替换。

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

编辑:更好的是,您可以只使用数组并在一行中完成所有操作

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2015-11-06
    • 2016-09-10
    • 1970-01-01
    • 2020-08-31
    • 2013-11-05
    相关资源
    最近更新 更多