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 image placeholders

The removeTemplateVariableImage method allows to remove an existing image in a document. The image to be removed must include a placeholder in its alternate text.

Here's the code to delete an image with a placeholder:

Deleting other contents (Advanced and Premium licenses only)

DOCXPath allows to remove almost any content in a document using removeWordContent: elements, contents by position, elements that don't use template placeholders...