2017-07-30 140 views
0

我正在使用PHPWord库用于通过我的PHP应用程序替换Word Doc中的一些占位符文本。PHPWord setValue不区分大小写的替换

我必须允许用户使用一些预定义的占位符来上传Word文档,例如, $ {} Anchor1$ {} Anchor2等

现在发生的事情是一些用户定义占位符$ {}作者1等

的setValue作品区分大小写的方式。

有任何PHPWord

使用 不区分大小写的替代通过setValue方法

问候

回答

0

没有为预定的选项,但在这里你可以做一些Monkey Patching

您可以修改源代码方法,但这不是一个好主意,因为如果将库更新为新版本,则会丢失更改。

取而代之,你可以创建一个新的类来扩展原来的类,并在那里添加一个调用原始的方法setValue但是它复制了参数以传递它们都是小写字母和大写。

这是我的方法。我无法尝试,但我认为它会起作用(当然,您可以为班级和方法选择一些更好的名称)。

class TemplateProcessorCaseInsensitive extends TemplateProcessor 
{ 
    public function setValueCaseInsensitive($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_DEFAULT) 
    { 
     if (is_array($search)) { 
      foreach ($search as &$item) { 
       $item = strtolower($item); 
      } 
      $capitalizedSearch = $search; 
      foreach ($capitalizedSearch as &$capitalizedItem){ 
       $capitalizedItem = ucfirst($capitalizedItem); 
      } 
      $search = array_merge($search, $capitalizedSearch); 
     } 
     else{ 
      $search = array(strtolower($search), ucfirst(strtolower($search))); 
     } 

     if(is_array($replace)){ 
      $replace = array_merge($replace, $replace); 
     } 
     else{ 
      $replace = array($replace, $replace); 
     } 

     $this->setValue($search, $replace, $limit); 
    } 
} 

让我们看看一些例子!

例1

如果你这样做:

$templateProcessor = new TemplateProcessorCaseInsensitive ('Template.docx'); 
$templateProcessor->setValueCaseInsensitive('Name', 'John Doe'); 

其实你是在后台做这个:

$templateProcessor = new TemplateProcessor('Template.docx'); 
$templateProcessor->setValue(array('name', 'Name'), array('John Doe', 'John Doe')); 

例2

如果你这样做:

$templateProcessor = new TemplateProcessorCaseInsensitive ('Template.docx'); 
$templateProcessor->setValueCaseInsensitive(array('City', 'Street'), array('Detroit', '12th Street')); 

其实你是在后台做这个:

$templateProcessor = new TemplateProcessor('Template.docx'); 
$templateProcessor->setValue(array('city', 'street', 'City', 'Street'), array('Detroit', '12th Street', 'Detroit', '12th Street'));