PHP 编辑 Microsoft Word 文档 str_replace 和 preg_replace 不起作用

2024-01-18

假设,我有 MSWord 文件 source.doc,其下一个内容是“Microsoft Word 文件的内容”。 例如,我想通过 PHP 打开它,并将单词“Microsoft”替换为“Openoffice”,并将结果保存到结果.doc。 这是使用的代码preg_replace:

$content = file_get_contents( SOMEPATH . '/source.doc' );
$new_content = preg_replace( '/Microsoft/i', 'Openoffice', $content );
file_put_contents( SOMEPATH . '/target.doc', $new_content );

或者使用str_replace:

$content = file_get_contents( SOMEPATH . '/source.doc' );
$new_content = str_replace( 'Microsoft', 'Openoffice', $content );
file_put_contents( SOMEPATH . '/target.doc', $new_content );

它们都不起作用。代码运行没有任何异常,但是目标.doc是相同的来源.doc。更换不执行。

我已经尝试了很多不同的接收方式,例如正则表达式修饰符、 iconv 等,但没有任何帮助。

var_dump of $content显示原始结构来源.doc里面充满了不寻常的人物,我想其中一些会停止str_replace or preg_replace扫描。无法弄清楚它是哪个字符以及如果找到它我该怎么办。

var_dump of $new_content与 $content 相同。

感谢转发任何帮助!


如果您有一个 DOCX 文件,您需要替换其中的某些内容,它基本上是一个压缩的 xml 存档。 以下示例介绍了如何在 DOCX 文件中将单词“Microsoft”替换为“Openoffice”。

$zip = new ZipArchive;
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
$wordDoc = "Document.docx";

if ($zip->open($wordDoc) === TRUE) {
    //Read contents into memory
    $oldContents = $zip->getFromName($fileToModify);
    //Modify contents:
    $newContents = str_replace('Microsoft', 'Openoffice', $oldContents);
    //Delete the old...
    $zip->deleteName($fileToModify);
    //Write the new...
    $zip->addFromString($fileToModify, $newContents);
    //And write back to the filesystem.
    $return =$zip->close();
    If ($return==TRUE){
        echo "Success!";
    }
} else {
    echo 'failed';
}

希望这可以帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP 编辑 Microsoft Word 文档 str_replace 和 preg_replace 不起作用 的相关文章

随机推荐