Finding and replacing text with PHPWord

Someone picture Someone · Nov 25, 2013 · Viewed 11.3k times · Source

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?

Answer

周秀坤 picture 周秀坤 · Oct 29, 2018

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}