How to remove template placeholders
phpdocx uses a syntax of its own to define placeholders in templates. Placeholders can be replaced with texts, images, WordFragments, HTML, other DOCX and so on.
After the exchange, it may happen that some placeholder remain unreplaced for lack of a value or maybe for not needing a value at all. These pending placeholders are very easy to remove.
Obtaining the existing placeholders
The getTemplateVariables method returns an array with all the existing placeholders in a DOCX. Each array key matches a document target, e.g., document for the document body, header or footnotes.
After calling placeholder replacement methods like replaceVariableByText or replaceVariableByHTML, and after the placeholder substitution, getTemplateVariables returns the unreplaced placeholders.
For example, the following code returns the placeholders of a document called template.docx.
For this example template, the output would be:
Deleting text placeholders
To delete a placeholder set in a template, run the method removeTemplateVariable. This method has three parameters:
- Placeholder name.
- Type of deletion: block erases the whole paragraph that contains the placeholder. Inline just deletes the placeholder.
- Target: document (default value), header, footer, footnote, endnote, comment.
For example, let's delete a placeholder called MYLINK, placed in the footer of the document (that's the target) with a em>inline type remove. The code is as follows:
If you want to delete all placeholders pending for a DOCX replacement, use this snippet:
Deleting images (Advanced and Premium licenses only)
The replacePlaceholderImage method allows to replace an existing image in a document by adding a placeholder in its alternate text. This same placeholder lets delete the image as well.
If you need to remove an image which has a placeholder in its alternate text, make use of the removeWordContent method of DOCXPath.
Here's the code to delete an image with a placeholder:
$VAR$ is the placeholder name, dollar signs included.