php word 添加,PHP 实现Office word 关键词添加背景色

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

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

下载项目目录如下

bVbhc7w?w=362&h=741

在路径 phpoffice/phpword/src/PhpWord/ 中新建文件 Template.php

namespace PhpOffice\PhpWord;

class Template extends TemplateProcessor

{

public $tempDocumentMainPart;

public function __construct($documentTemplate)

{

parent::__construct($documentTemplate);

}

static $wordArr;

static $color = 'yellow';

/**

* 多个词替换目前替换背景色功能

*

* @param $word

* @param $color

* @example {

* $template = new \PhpOffice\PhpWord\Template($path);

* $template->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(

'/]*)>((?:(?!)[\s\S])*)]*>((?:(?!)[\s\S])*)]*>/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('/]*>(?:(?!)[\s\S])*]*>]*>/iUs', '', $matches[0]);

}

}

return $matches[0];

},

$content);

}

}

第二部就扩展完成背景色替换功能,接下怎样调用?

//引入类库

require autoload.php

$path = './test.docx';

$template = new \PhpOffice\PhpWord\Template($path);

$template->setWordArrBgColor(['TMD', '台湾省', 'Caonima'], 'yellow');

效果

bVbhddu?w=960&h=333

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值