2015-11-11 99 views
2

我正在使用PHPWord來讀取我的docx模板,並在處理結束時從模板中刪除所有搜索模式。在DOCX模板中的搜索模式是PHPWord - 從Word文檔中刪除所有搜索模式

${SOMETAG} 
text block 
${/SOMETAG} 

的DOCX背後的XML有看起來像這樣的結構:

<w:p w:rsidR="00E21534" w:rsidRDefault="00E21534" w:rsidP="00E21534"><w:r><w:t>${SOMETAG}</w:t></w:r></w:p><w:p w:rsidR="00E21534" w:rsidRDefault="00E21534" w:rsidP="00E21534"><w:r><w:t>text block</w:t></w:r></w:p><w:p w:rsidR="00E21534" w:rsidRDefault="00E21534" w:rsidP="00E21534"><w:r><w:t>${/SOMETAG}</w:t></w:r></w:p> 

這是我寫刪除開始標記功能即$ {SOMETAG},但它似乎無法找到標籤。我認爲問題在於我的preg_match_all中的模式。你能告訴我我在這裏做錯了嗎?

public function removeSearchPatterns() 
{ 
    //search for ${*} 
    preg_match_all(
     '/(${.*})/is', 
     $this->tempDocumentMainPart, 
     $matches, 
     PREG_SET_ORDER 
    ); 

    //remove ${*} 
    foreach ($matches as $match){ 
     if (isset($match[0])) { 
      $this->tempDocumentMainPart = str_replace(
       $match[0], 
       '', 
       $this->tempDocumentMainPart 
      ); 
     } 
    } 

} 

回答

0

我做到了!儘管建議更有效的方式是值得歡迎的。

public function removeSearchPatterns() 
{ 
    //search for ${*} and ${/*} 
    preg_match_all(
     '/(\${)(\b[^}]*)(})(.*?)(\${.)(\2)(})/', 
     $this->temporaryDocumentMainPart, 
     $matches, 
     PREG_SET_ORDER 
    ); 
    //if ${*} and ${/*} are found, do the removal 
    if (!empty($matches)){ 
     //remove ${*} and ${/*} 
     foreach ($matches as $match){    
      if (isset($match[0])) { 
       $this->temporaryDocumentMainPart = str_replace(
        $match[0], 
        $match[4], 
        $this->temporaryDocumentMainPart 
       ); 
      } 
     } 

     //search for <w:p> to </w:p> 
     preg_match_all(
      '/(<w:p[^>]*><w:r[^>]*><w:t><\/w:t><\/w:r>)(?:<[^<>]+><[^<>]+>)?(<\/w:p>)/', 
      $this->temporaryDocumentMainPart, 
      $matches, 
      PREG_SET_ORDER 
     ); 

     //remove <w:p> to </w:p> 
     foreach ($matches as $match){ 
      if (isset($match[0])) {    
       $this->temporaryDocumentMainPart = str_replace(
        $match[0], 
        '', 
        $this->temporaryDocumentMainPart 
       ); 
      } 
     } 
    } 
} 
0

我會根據您的代碼的方法,但我簡化到只刪除$ {}和$ {/}。順便說一下,感謝上面的代碼。

public function removeSearchPatterns() 
{ 
    //search for ${*} and ${/*} 
    preg_match_all(
     '/(\$\{[^\}]*\})/', 
     $this->temporaryDocumentMainPart, 
     $matches, 
     PREG_SET_ORDER 
    ); 

    //remove ${*} and ${/*} 
    foreach ($matches as $match){ 
     $this->temporaryDocumentMainPart = str_replace(
      $match, 
      '', 
      $this->temporaryDocumentMainPart 
     ); 
    } 
}