需求:最近需要从wold中读出一个word新闻规范扫描工具,用于扫描可疑和错误的word文本,并对错误的可疑文本添加背景色。内容扫描规范识别本文不做介绍,重点介绍如何通过编程语言操作word给文本添加背景色。为了快速实现效果,直接在https://github.com/PHPOffice/...上扩展功能本项目:下载项目目录如下,在phpoffice/phpword/路径下新建文件Template.php源代码/PhpWord/setWordBgColor($txt,'黄色');*}*/publicfunctionsetWordArrBgColor($word,$color){self::$wordArr=array_unique($word);}如果(!empty(self::$wordArr)){self::$color=$color;$this->tempDocumentHeaders=$this->_replace($this->tempDocumentHeaders);$this->tempDocumentMainPart=$this->_replace($this->tempDocumentMainPart艺术);$this->tempDocumentFooters=$this->_replace($this->tempDocumentFooters);}}privatefunction_replace($content){returnpreg_replace_callback('/]*)>((?:(?!<\w:r>)[\s\S])*)]*>((?:(?!<\/w:r>)[\s\S])*)<\/w:t><\/w:r[^>]*>/iUs',function($matches){//print_r($matches);if(!empty(trim($matches[3]))){$text=$matches[3];foreach(self::$wordArrAS$value){//判断字符串中是否存在关键字if(false!==strpos($text,$value)){//背景色属性$bgAttr=empty($matches[2])?'':str_ireplace('','',$matches[2]);$matches[0]=str_ireplace($value,''.$bgAttr.''.$value.''.$bgAttr.'',$matches[0]);}}if(!empty($matches[0])){//过滤掉空的$matches[0]=preg_replace('/]*>(?:(?!<\w:t>)[\s\S])*]*><\/w:t><\/w:r[^>]*>/iUs','',$matches[0]);}}return$matches[0];},$content);}}第二个部分会展开完成背景色替换功能,接下来怎么调用?//引入类库requireautoload.php$path='./test.docx';$template=new\PhpOffice\PhpWord\Template($path);$template->setWordArrBgColor(['TMD','台湾省','曹尼玛'],'黄色');效果