>  기사  >  백엔드 개발  >  PHP를 사용하여 단어의 키워드에 배경색을 추가하는 방법

PHP를 사용하여 단어의 키워드에 배경색을 추가하는 방법

不言
不言앞으로
2018-10-09 13:59:362749검색

이 글의 내용은 PHP에서 단어에 배경색을 추가하는 방법에 대한 내용입니다. 필요한 친구들이 참고하시면 좋을 것 같습니다.

요구 사항: 최근 단어 뉴스 표준 스캔 도구를 만들었습니다. 단어의 내용을 읽고, 의심스럽고 잘못된 단어 텍스트를 스캔하고, 잘못되고 의심스러운 단어에 배경색을 추가해야 합니다. 텍스트.
컨텐츠 스캔 사양 식별은 이 글에서 설명하지 않습니다. Key points 프로그래밍 언어 운영을 통해 텍스트에 배경색을 추가하는 방법에 대해 이야기합니다. 단어 .

빠른 효과를 얻기 위해 기능을 https://github.com/PHPOffice/에서 직접 확장했습니다... 이 프로젝트:

  • # 🎜 🎜#다운로드 프로젝트 디렉토리는 다음과 같습니다

PHP를 사용하여 단어의 키워드에 배경색을 추가하는 방법

  • phpoffice/phpword/src/PhpWord/

<?php namespace PhpOffice\PhpWord;

class Template extends TemplateProcessor
{
    public $tempDocumentMainPart;

    public function __construct($documentTemplate)
    {
        parent::__construct($documentTemplate);
    }

    static $wordArr;
    static $color = &#39;yellow&#39;;

    /**
     * 多个词替换目前替换背景色功能
     *
     * @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(
            '/<r>]*)>((?:(?!)[\s\S])*)<t>]*>((?:(?!)[\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])
                                ? '<rpr><highlight></highlight></rpr>'
                                : str_ireplace('', '<highlight></highlight>', $matches[2]);

                            $matches[0] = str_ireplace($value,
                                '</t></r><r>'.$bgAttr.'<t>'.$value.'</t></r><r>'.$bgAttr.'<t>',
                                $matches[0]);
                        }
                    }


                    if (!empty($matches[0])) {

                        // 过滤掉空的
                        $matches[0] = preg_replace('/<r>]*>(?:(?!)[\s\S])*<t>]*>]*>/iUs', '', $matches[0]);
                    }
                }
                return $matches[0];
            },
            $content);
    }
}</t></r></t></r>
  • 경로에 Template.php 새 파일을 만듭니다. 배경색 교체 기능을 확장하고 완성하는 것입니다. 다음에는 어떻게 호출하나요?

//引入类库
require autoload.php
$path = './test.docx';
$template = new \PhpOffice\PhpWord\Template($path);
$template->setWordArrBgColor(['TMD', '台湾省', 'Caonima'], 'yellow');

위 내용은 PHP를 사용하여 단어의 키워드에 배경색을 추가하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제