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
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}
-
-
your solution did not work for me. I have used
setValue
but this is not replacing the given value. Thanks a lot.– KamleshCommented Dec 1, 2023 at 11:57
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:
- Rename xxx.docx to xxx.zip
- Unzip to a temporary folder
- In temporary_folder/word read in document.xml which contains all text of the document (except headers and footers)
- Replace what you need to replace
- Save the document.xml
- 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.
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
-
Is there a way to replace placeholders in a link? I have been trying to do this but doesn't work with setValue()– VishnuCommented Dec 24, 2015 at 13:15