【问题标题】:PHPWord setValue case insensitive replacementPHPWord setValue 不区分大小写替换
【发布时间】:2018-01-06 00:52:46
【问题描述】:

我正在使用 PHPWord 库通过我的 PHP 应用程序替换 Word Doc 中的一些占位符文本。

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

现在发生的情况是一些用户将占位符定义为 ${author1} 等。

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

有什么方法可以通过 PHPWord 中的 setValue 使用 不区分大小写的替换

问候

【问题讨论】:

    标签: php case-sensitive case-insensitive phpword setvalue


    【解决方案1】:

    没有预定义的选项,但在这里你可以做一些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'));
    

    【讨论】:

      猜你喜欢
      • 2010-10-29
      • 2014-02-16
      • 1970-01-01
      • 2013-10-19
      • 2011-08-05
      • 2017-07-19
      • 2013-12-13
      • 2011-12-22
      相关资源
      最近更新 更多