20

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?

3 Answers 3

13

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}

Sign up to request clarification or add additional context in comments.

2 Comments

your solution did not work for me. I have used setValue but this is not replacing the given value. Thanks a lot.
7

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.

Comments

7

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

1 Comment

Is there a way to replace placeholders in a link? I have been trying to do this but doesn't work with setValue()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.