zel*_*oba 2 php ms-word preg-replace str-replace
假设,我有MSWord文件source.doc,下一个内容是"Microsoft Word文件的内容".例如,我想通过PHP打开它并将单词"Microsoft"替换为"Openoffice"并将结果保存到result.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 );
Run Code Online (Sandbox Code Playgroud)
或使用str_replace:
$content = file_get_contents( SOMEPATH . '/source.doc' );
$new_content = str_replace( 'Microsoft', 'Openoffice', $content );
file_put_contents( SOMEPATH . '/target.doc', $new_content );
Run Code Online (Sandbox Code Playgroud)
它们都不起作用.代码运行没有任何异常,但target.doc与source.doc相同.替换不执行.
我尝试了很多不同的接收器,比如正则表达式修改器,iconv等等,但没有任何帮助.
var_dump的$content示出的原始结构source.doc即充满不寻常的字符和作为我想一些它停止str_replace或preg_replace扫描.无法弄清楚它是哪个字符,如果我找到它我该怎么办.
var_dump的$new_content是相同的$内容.
感谢您的帮助!
Sha*_*n01 12
如果你有一个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';
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
11486 次 |
| 最近记录: |