Replacing text in a Word document with PHP

  • Jul 23, 2012


This post is outdated. For up date information about replacing contents please refer to the Practical guide.

Although PHPDocX has multiple tools to work with Word templates they require the preprocessing of the template.

Even if that preprocessing is extremely simple and should not cause any trouble, there are occasions in which we may not have that option or there is the need to work with many pre-existing Word documents and that procedure may be time consuming.

The new DocxUtilities class of PHPDocX (available in PRO+ and CORPORATE versions since v2.5.3) allow to replace an string of text in a Word document by any other string of text, preserving all of its styles, with only a single line of code and, more importantly, without the need of any kind of prior manipulation of the corresponding Word document.

The required code is extremely simple:

require_once 'path_to_phpdocx/classes/';
$newDocx = new DocxUtilities();
$newDocx->searchAndReplace('source.docx', 'target.docx', 'search string', 'replacement string')

By default the searchAndReplace method only searches the body of the document (to improve performance), but if one wishes to search and replace the string of text in headers, footers, comments, etcetera, this can be simply achieved via the options parameter:

require_once 'path_to_phpdocx/classes/';
$newDocx = new DocxUtilities();
$options = array( 'document' => true,
'endnotes' => true,
'comments' => true,
'headersAndFooters' => true,
'footnotes' => true);
$newDocx->searchAndReplace('source.docx', 'target.docx', 'search string', 'replacement string', $options);

With this additional functionality to change some text in an existing Word document is just a piece of cake!!