博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PHP 实现Office word 关键词添加背景色
阅读量:6938 次
发布时间:2019-06-27

本文共 2266 字,大约阅读时间需要 7 分钟。

需求:最近做一个word新闻规范扫描的工具,需要将wold中的内容读取出来扫描可疑、错误词文本,并将错误可疑文本添加背景颜色。

内容扫描规范识别不在本文中描述,重点说怎样通过编程语言操作word实现文字添加背景色

为了能快速达到效果,直接在 这个项目上扩展的功能:

  • 项目目录如下

clipboard.png

  • 在路径 phpoffice/phpword/src/PhpWord/ 中新建文件 Template.php
setWordBgColor($txt, 'yellow'); * } */ public function setWordArrBgColor($word, $color) { self::$wordArr = array_unique($word); if (!empty(self::$wordArr)) { self::$color = $color; $this->tempDocumentHeaders = $this->_replace($this->tempDocumentHeaders); $this->tempDocumentMainPart = $this->_replace($this->tempDocumentMainPart); $this->tempDocumentFooters = $this->_replace($this->tempDocumentFooters); } } private function _replace($content) { return preg_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::$wordArr AS $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); }}
  • 第二部就扩展完成背景色替换功能,接下怎样调用?
//引入类库require autoload.php$path = './test.docx';$template = new \PhpOffice\PhpWord\Template($path);$template->setWordArrBgColor(['TMD', '台湾省', 'Caonima'], 'yellow');
  • 效果

clipboard.png

转载地址:http://mdbnl.baihongyu.com/

你可能感兴趣的文章
阿里的分布式持续集成系统-reliable
查看>>
【转】单日峰值2T发送量邮件营销平台实践经验
查看>>
Dell Compellent的一些缺陷
查看>>
我的友情链接
查看>>
分布式消息系统 Kafka 简介
查看>>
内部控制
查看>>
iOS地图选址
查看>>
我的友情链接
查看>>
自动监控linux服务器负载并重启Web服务的脚本
查看>>
四、Windows Server 2012R2 Hyper-v虚拟交换机的创建与管理
查看>>
java 运算顺序
查看>>
天涯LVS部署
查看>>
eclipse不能自动编译工程的解决方法
查看>>
最好用的cisco路由模拟器 debianIOL
查看>>
Shpinx在PHPCMS里的使用及配置
查看>>
Linux Oracle Rac 10G 搭建& Patch
查看>>
django models.py模块的外部引用
查看>>
VMware虚拟化技术培训(8) 虚拟机管理之二
查看>>
spring内部各模块jar包依赖
查看>>
Apache与Nginx网络模型对比
查看>>