PHP编辑Microsoft Word文档str#u replace和preg#u replace don';行不通

PHP编辑Microsoft Word文档str#u replace和preg#u replace don';行不通,php,ms-word,preg-replace,str-replace,Php,Ms Word,Preg Replace,Str Replace,假设,我得到了MSWord文件source.doc,下一个内容是“Microsoft Word文件的内容”。 例如,我想通过PHP打开它,将单词“Microsoft”替换为“Openoffice”,并将结果保存到result.doc中。 以下是使用preg\u replace的代码: $content = file_get_contents( SOMEPATH . '/source.doc' ); $new_content = preg_replace( '/Microsoft/i', 'Ope

假设,我得到了MSWord文件source.doc,下一个内容是“Microsoft Word文件的内容”。 例如,我想通过PHP打开它,将单词“Microsoft”替换为“Openoffice”,并将结果保存到result.doc中。 以下是使用
preg\u replace
的代码:

$content = file_get_contents( SOMEPATH . '/source.doc' );
$new_content = preg_replace( '/Microsoft/i', 'Openoffice', $content );
file_put_contents( SOMEPATH . '/target.doc', $new_content );
$content = file_get_contents( SOMEPATH . '/source.doc' );
$new_content = str_replace( 'Microsoft', 'Openoffice', $content );
file_put_contents( SOMEPATH . '/target.doc', $new_content );
或使用
str\u replace

$content = file_get_contents( SOMEPATH . '/source.doc' );
$new_content = preg_replace( '/Microsoft/i', 'Openoffice', $content );
file_put_contents( SOMEPATH . '/target.doc', $new_content );
$content = file_get_contents( SOMEPATH . '/source.doc' );
$new_content = str_replace( 'Microsoft', 'Openoffice', $content );
file_put_contents( SOMEPATH . '/target.doc', $new_content );
它们都不起作用。代码运行时没有任何异常,但target.doc与source.doc相同。替换不执行

我尝试了很多不同的接收器,比如正则表达式修改器、iconv等等,但没有任何帮助

$content
var\u dump
显示了source.doc的原始结构,其中充满了不寻常的字符,并且我认为其中一些会停止
str\u replace
preg\u replace
扫描。我弄不清是哪个字符,如果我能找到它该怎么办

$new\u content
var\u dump
与$content相同


谢谢你的帮助

我想这就是你想要的:)因为doc文件不是普通的文本文件(试着用记事本打开一个……你会明白我的意思)

如果你有一个DOCX文件,你需要替换其中的内容,它基本上是一个压缩的xml存档。 下面是一个关于如何在DOCX文件中用“Openoffice”替换单词“Microsoft”的示例

$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';
}

希望这有帮助

MS Word以压缩格式保存其文件,因此如果不先解压缩,您将无法查看或编辑内容。但是,即使这样做,您也必须知道文件格式的详细信息(有几种),并且不能保证页面上的一个单词在文件中保存为连续字符。请记住,PHPWord项目只允许您打开和操作DOCX文件(压缩的openXML格式文件)。如果你需要处理较旧的文档格式,它将不起作用。如果你还添加了源代码作为答案的链接,那将是一件好事。你的意思是什么?源代码,或者其他源代码的链接?啊,对不起。我误解了答案。我以为你从谷歌找到了答案。如果是这样的话,链接到源代码将是一件好事。无论如何,欢迎使用堆栈溢出。这非常有效!!但是有一个提示,因为这给了我一些悲伤。如果您像我一样使用替换代码(例如{MYVAL}等),并且它没有更改…将更改的内容发送到浏览器并进行检查。在替换代码中会发现大量xml垃圾。相应地构造代码。在这种情况下,如何替换许多字符串?比如$newContents1=str_replace('Microsoft1','Openoffice1',$oldContents)$newContents2=str_replace('Microsoft2','Openoffice2',$oldContents);