From 8dc276a0db8321b5541f32a8eb58536848c8f00e Mon Sep 17 00:00:00 2001 From: Roman Syroeshko Date: Sun, 16 Aug 2015 20:20:13 +0400 Subject: [PATCH] Merged #513. --- src/PhpWord/TemplateProcessor.php | 41 ++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 50bccb8544..512768632c 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -82,16 +82,16 @@ public function __construct($documentTemplate) $this->zipClass = new ZipArchive(); $this->zipClass->open($this->temporaryDocumentFilename); $index = 1; - while ($this->zipClass->locateName($this->getHeaderName($index)) !== false) { + while (false !== $this->zipClass->locateName($this->getHeaderName($index))) { $this->temporaryDocumentHeaders[$index] = $this->zipClass->getFromName($this->getHeaderName($index)); $index++; } $index = 1; - while ($this->zipClass->locateName($this->getFooterName($index)) !== false) { + while (false !== $this->zipClass->locateName($this->getFooterName($index))) { $this->temporaryDocumentFooters[$index] = $this->zipClass->getFromName($this->getFooterName($index)); $index++; } - $this->temporaryDocumentMainPart = $this->zipClass->getFromName('word/document.xml'); + $this->tempDocumentMainPart = $this->fixBrokenMacros($this->zipClass->getFromName('word/document.xml')); } /** @@ -175,7 +175,7 @@ public function getVariables() */ public function cloneRow($search, $numberOfClones) { - if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') { + if ('${' !== substr($search, 0, 2) && '}' !== substr($search, -1)) { $search = '${' . $search . '}'; } @@ -345,6 +345,31 @@ public function saveAs($fileName) unlink($tempFileName); } + /** + * Finds parts of broken macros and sticks them together. + * Macros, while being edited, could be implicitly broken by some of the word processors. + * + * @since 0.13.0 + * + * @param string $documentPart The document part in XML representation. + * + * @return string + */ + protected function fixBrokenMacros($documentPart) + { + $fixedDocumentPart = $documentPart; + + $fixedDocumentPart = preg_replace_callback( + '|\$\{([^\}]+)\}|U', + function ($match) { + return strip_tags($match[0]); + }, + $fixedDocumentPart + ); + + return $fixedDocumentPart; + } + /** * Find and replace placeholders in the given XML section. * @@ -356,14 +381,6 @@ public function saveAs($fileName) */ protected function setValueForPart($documentPartXML, $search, $replace, $limit) { - $pattern = '|\$\{([^\}]+)\}|U'; - preg_match_all($pattern, $documentPartXML, $matches); - foreach ($matches[0] as $value) { - $valueCleaned = preg_replace('/<[^>]+>/', '', $value); - $valueCleaned = preg_replace('/<\/[^>]+>/', '', $valueCleaned); - $documentPartXML = str_replace($value, $valueCleaned, $documentPartXML); - } - if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') { $search = '${' . $search . '}'; }