Forum


Replies: 1   Views: 499
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 ordersvrc  · 20-06-2023 - 18:59

The actual goal of my function is to replace all ssn's in a document with 'xxx-xx-xxxx'; however searchAndReplace method does not allow regex.   

My workaround is to getWordContents, get the ssn's using regex there and then create an array of 'ssn' that I can search and replace.

The problem is, that It looks like right now, the searchAndReplace  method only allows you to do one string and it outputs a file so i cannot iterate over my array.  

Is there a better solution or a method I'm unaware of?

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.