Someone
Someone

Reputation: 372

Finding and replacing text with PHPWord

Is it possible to just do a simple find and replace for text on a Word document using PHPWord? From what I've seen, the closest you can get is just ADDING text to a section, and you can't manipulate existing text except for font, etc. If not, is there anything free that I can use to do this?

Upvotes: 20

Views: 18214

Answers (3)

周秀坤
周秀坤

Reputation: 131

Install

composer require phpoffice/phpword

PHP code

include 'vendor/autoload.php';
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('test2.docx');
$templateProcessor->setValue('name', 'myvar');
$templateProcessor->saveAs('./xx.docx');

My test.docx just has the word: ${name}

Upvotes: 13

Diego Vieira
Diego Vieira

Reputation: 1149

You can use setValue in order to achieve what you are looking for. Take a look at the samples.

Here is the method: https://github.com/PHPOffice/PHPWord/blob/e35838f7d7928b2308df3f7f0ef6d49bf96f453c/src/PhpWord/Template.php#L131

Upvotes: 7

mainguy
mainguy

Reputation: 8331

No, PHPWord is only intented to create docx files.

Anyhow, a docx file is simply a collection of xml files in a zip container. In general what you need to do is:

  1. Rename xxx.docx to xxx.zip
  2. Unzip to a temporary folder
  3. In temporary_folder/word read in document.xml which contains all text of the document (except headers and footers)
  4. Replace what you need to replace
  5. Save the document.xml
  6. Zip the whole temporary folder back to xxx.docx

Beware that Word has a tendency to split words in multiple sections, depending on what was done with the document at save point. There may be Bookmarks, language changes, spellchecking or character formating tags in the middle of any word.

Good luck to find a safe way to handle this.

Upvotes: 7

Related Questions