Home>Article>Backend Development> How to add background color to keywords in word using php
The content of this article is about how to add background color to keywords in word in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Requirements: I recently made a word news standard scanning tool. It needs to read the content in word, scan suspicious and wrong word text, and add a background color to the wrong and suspicious text.
Content scanning specification recognition is not described in this article.Key pointstalk about how to add background color to textby operating word inprogramming language.
In order to achieve the effect quickly, directly expand the functions on https://github.com/PHPOffice/... This project:
Download the project directory as follows
Create a new file Template.php in the path phpoffice/phpword/src/PhpWord/
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); } }
The second part will expand the background color replacement function. How to call it next?
//引入类库 require autoload.php $path = './test.docx'; $template = new \PhpOffice\PhpWord\Template($path); $template->setWordArrBgColor(['TMD', '台湾省', 'Caonima'], 'yellow');
The above is the detailed content of How to add background color to keywords in word using php. For more information, please follow other related articles on the PHP Chinese website!