PHP Word – Remove placeholder from template so it does not leave a gap (blank line)

Solution for PHP Word – Remove placeholder from template so it does not leave a gap (blank line)
is Given Below:

I’m using PHPWord to generate reports based on a template.

I replace placeholders in that template

$templateProcessor = new TemplateProcessor('template.docx');
$templateProcessor->setValue('placeholder_name', 'value5123');

and save the new file

$templateProcessor->saveAs('report.docx');

Pretty straightforward.

However, there are some values which are optional, so they leave stray placeholders behind, and the best I’ve been able to do is replace them with an empty string, which still leaves blank lines.

Is there a way to remove the placeholder expression altogether and prevent it (and the blank line) from showing in the final file?

Thanks