Bolt\Helpers\Excerpt::extractRelevant PHP Method

extractRelevant() private method

Center on, and highlight search terms in excerpts.
private extractRelevant ( string | array $words, string $fulltext, integer $relLength = 300 ) : mixed | string
$words string | array
$fulltext string
$relLength integer
return mixed | string
    private function extractRelevant($words, $fulltext, $relLength = 300)
    {
        if (!is_array($words)) {
            $words = explode(' ', $words);
        }
        // 1/6 ratio on prevcount tends to work pretty well and puts the terms
        // in the middle of the extract
        $prevCount = floor($relLength / 6);
        $indicator = '…';
        $textlength = strlen($fulltext);
        if ($textlength <= $relLength) {
            return $fulltext;
        }
        $locations = $this->extractLocations($words, $fulltext);
        $startPos = $this->determineSnipLocation($locations, $prevCount);
        // if we are going to snip too much...
        if ($textlength - $startPos < $relLength) {
            $startPos = $startPos - ($textlength - $startPos) / 2;
        }
        $relText = substr($fulltext, $startPos, $relLength);
        // check to ensure we dont snip the last word if thats the match
        if ($startPos + $relLength < $textlength) {
            $relText = substr($relText, 0, strrpos($relText, ' ')) . $indicator;
            // remove last word
        }
        // If we trimmed from the front add '…'
        if ($startPos != 0) {
            $relText = $indicator . substr($relText, strpos($relText, ' ') + 1);
            // remove first word
        }
        // Highlight the words, using the `<mark>` tag.
        foreach ($words as $word) {
            $relText = preg_replace('/\\b(' . $word . ')\\b/i', '<mark>$1</mark>', $relText);
        }
        return $relText;
    }