|
導(dǎo)讀網(wǎng)頁(yè)的本質(zhì)就是超級(jí)文本標(biāo)記語(yǔ)言,通過(guò)結(jié)合使用其他的Web技術(shù)(如:腳本語(yǔ)言、公共網(wǎng)關(guān)接口、組件等),可以創(chuàng)造出功能強(qiáng)大的網(wǎng)頁(yè)。因而,超級(jí)文本標(biāo)記語(yǔ)言是萬(wàn)維網(wǎng)(Web)編程的基礎(chǔ),也就是說(shuō)萬(wàn)維網(wǎng)是建立... 網(wǎng)頁(yè)的本質(zhì)就是超級(jí)文本標(biāo)記語(yǔ)言,通過(guò)結(jié)合使用其他的Web技術(shù)(如:腳本語(yǔ)言、公共網(wǎng)關(guān)接口、組件等),可以創(chuàng)造出功能強(qiáng)大的網(wǎng)頁(yè)。因而,超級(jí)文本標(biāo)記語(yǔ)言是萬(wàn)維網(wǎng)(Web)編程的基礎(chǔ),也就是說(shuō)萬(wàn)維網(wǎng)是建立在超文本基礎(chǔ)之上的。超級(jí)文本標(biāo)記語(yǔ)言之所以稱為超文本標(biāo)記語(yǔ)言,是因?yàn)槲谋局邪怂^“超級(jí)鏈接”點(diǎn)。 本篇文章給大家?guī)?lái)的內(nèi)容是關(guān)于php如何實(shí)現(xiàn)word中關(guān)鍵詞添加背景色的方法,有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)你有所幫助。需求:最近做一個(gè)word新聞規(guī)范掃描的工具,需要將wold中的內(nèi)容讀取出來(lái)掃描可疑、錯(cuò)誤詞文本,并將錯(cuò)誤可疑文本添加背景顏色。 為了能快速達(dá)到效果,直接在https://github.com/PHPOffice/... 這個(gè)項(xiàng)目上擴(kuò)展的功能:
<?php
namespace PhpOffice\PhpWord;
class Template extends TemplateProcessor
{
public $tempDocumentMainPart;
public function __construct($documentTemplate)
{
parent::__construct($documentTemplate);
}
static $wordArr;
static $color = 'yellow';
/**
* 多個(gè)詞替換目前替換背景色功能
*
* @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(
'/<w:r w:([^>]*)>((?:(?!<\w:r>)[\s\S])*)<w:t[^>]*>((?:(?!<\/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) {
// 判斷關(guān)鍵詞在字符串中是否存在
if (false !== strpos($text, $value)) {
// 背景色屬性
$bgAttr = empty($matches[2])
? '<w:rPr><w:highlight w:val="'.self::$color.'"/></w:rPr>'
: str_ireplace('</w:rPr>', '<w:highlight w:val="'.self::$color.'"/></w:rPr>', $matches[2]);
$matches[0] = str_ireplace($value,
'</w:t></w:r><w:r w:'.$matches[1].'>'.$bgAttr.'<w:t>'.$value.'</w:t></w:r><w:r w:'.$matches[1].'>'.$bgAttr.'<w:t>',
$matches[0]);
}
}
if (!empty($matches[0])) {
// 過(guò)濾掉空的
$matches[0] = preg_replace('/<w:r w:[^>]*>(?:(?!<\w:t>)[\s\S])*<w:t[^>]*><\/w:t><\/w:r[^>]*>/iUs', '', $matches[0]);
}
}
return $matches[0];
},
$content);
}
}
//引入類庫(kù) require autoload.php $path = './test.docx'; $template = new \PhpOffice\PhpWord\Template($path); $template->setWordArrBgColor(['TMD', '臺(tái)灣省', 'Caonima'], 'yellow'); 以上就是php如何實(shí)現(xiàn)word中關(guān)鍵詞添加背景色的方法的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章! 網(wǎng)站建設(shè)是一個(gè)廣義的術(shù)語(yǔ),涵蓋了許多不同的技能和學(xué)科中所使用的生產(chǎn)和維護(hù)的網(wǎng)站。 |
溫馨提示:喜歡本站的話,請(qǐng)收藏一下本站!