TeamTNT\TNTSearch\Support\Highlighter::highlight PHP Метод

highlight() публичный Метод

public highlight ( $text, $needle, $tag = 'em', $options = [] )
    public function highlight($text, $needle, $tag = 'em', $options = [])
    {
        $this->options = array_merge($this->options, $options);
        $highlight = '<' . $tag . '>\\1</' . $tag . '>';
        $needle = preg_split('/\\PL+/u', $needle, -1, PREG_SPLIT_NO_EMPTY);
        // Select pattern to use
        if ($this->options['simple']) {
            $pattern = '#(%s)#';
            $sl_pattern = '#(%s)#';
        } else {
            $pattern = '#(?!<.*?)(%s)(?![^<>]*?>)#';
            $sl_pattern = '#<a\\s(?:.*?)>(%s)</a>#';
        }
        // Case sensitivity
        if (!$this->options['caseSensitive']) {
            $pattern .= 'i';
            $sl_pattern .= 'i';
        }
        $needle = (array) $needle;
        foreach ($needle as $needle_s) {
            $needle_s = preg_quote($needle_s);
            // Escape needle with optional whole word check
            if ($this->options['wholeWord']) {
                $needle_s = '\\b' . $needle_s . '\\b';
            }
            // Strip links
            if ($this->options['stripLinks']) {
                $sl_regex = sprintf($sl_pattern, $needle_s);
                $text = preg_replace($sl_regex, '\\1', $text);
            }
            $regex = sprintf($pattern, $needle_s);
            $text = preg_replace($regex, $highlight, $text);
        }
        return $text;
    }

Usage Example

Пример #1
0
 public function testHighlight()
 {
     $hl = new Highlighter();
     $text = "This is some text";
     $output = $hl->highlight($text, "is text", 'em', ['wholeWord' => false]);
     $this->assertEquals("Th<em>is</em> <em>is</em> some <em>text</em>", $output);
     $output = $hl->highlight($text, "is text", 'em', ['wholeWord' => true]);
     $this->assertEquals("This <em>is</em> some <em>text</em>", $output);
     $output = $hl->highlight($text, "this text", 'em', ['caseSensitive' => true]);
     $this->assertEquals("This is some <em>text</em>", $output);
     $output = $hl->highlight($text, "this text", 'em', ['caseSensitive' => false]);
     $this->assertEquals("<em>This</em> is some <em>text</em>", $output);
     $output = $hl->highlight($text, "text", 'em');
     $this->assertEquals("This is some <em>text</em>", $output);
     $output = $hl->highlight($text, "text", 'b');
     $this->assertEquals("This is some <b>text</b>", $output);
 }
All Usage Examples Of TeamTNT\TNTSearch\Support\Highlighter::highlight