Forum


Replies: 1   Views: 339
Search and replace with array
Topic closed:
Please note this is an old forum thread. Information in this post may be out-to-date and/or erroneous.
Every phpdocx version includes new features and improvements. Previously unsupported features may have been added to newer releases, or past issues may have been corrected.
We encourage you to download the current phpdocx version and check the Documentation available.

Posted by admin  · 20-06-2023 - 19:53

Hello,

Since phpdocx 12.5 (https://www.phpdocx.com/news/post/phpdocx-v12-5-release-notes/224), searchAndReplace allows using strings and arrays to replace contents:

DocxUtilities: searchAndReplace, searchAndRemove and searchAndHighlight methods allow using arrays (Advanced and Premium licenses).

From the API documentation page:

search

The string of text or array that you want to replace.

replace

The string of text or array that you want to include.

Please check the following included in the package (DocxUtilities/searchAndReplace/sample_2.php):

$docx = new DocxUtilities();

$options = array(
    'document' => true,
    'endnotes' => true,
    'comments' => true,
    'headersAndFooters' => true,
    'footnotes' => true,
);

$searchTerms = array(
    'data',
    'Another',
    'Some',
    'More',
    'comment',
);
$replaceTerms = array(
    'required data',
    'Other',
    'SOME',
    'MORE',
    'my comment',
);
$docx->searchAndReplace('../../files/second.docx', 'example_searchAndReplace_2.docx', $searchTerms, $replaceTerms, $options);

Using previous versions of phpdocx you need to call searchAndReplace as many times as needed, generating a new file for each string to be replaced.

This method supports plain texts, but not regex, so your approach is correct to get dynamically the content to be replaced.

Regards.