Skip to content

Commit

Permalink
添加搜索结果高亮显示功能
Browse files Browse the repository at this point in the history
  • Loading branch information
vanry committed Jun 25, 2018
1 parent d360662 commit 3331ccf
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
29 changes: 27 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,6 @@ php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"


```php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
Expand Down Expand Up @@ -139,5 +137,32 @@ class Post extends Model

分别在 `config/scout.php` 中的 `jieba`, `phpanalysis``scws` 中修改配置。

## 高亮

`view composer` 中引入 `highlighter`

```php
use Vanry\Scout\Highlighter;

// ...

view()->composer('search', function ($view) {
$tokenizer = app('tntsearch.tokenizer')->driver();

$view->with('highlighter', new Highlighter($tokenizer));
});
```

```php
// search.blade.php

{!! $highlighter->highlight($article->title, $query) !!}

{!! $highlighter->highlight($article->excerpt, $query) !!}
```

> 默认使用 `em` 作为高亮标签,在 `css` 中设置样式即可。
## 教程

[laravel下TNTSearch+jieba-php实现全文搜索](https://baijunyao.com/article/154)
34 changes: 34 additions & 0 deletions src/Highlighter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Vanry\Scout;

use TeamTNT\TNTSearch\Support\Tokenizer;
use TeamTNT\TNTSearch\Support\TokenizerInterface;

class Highlighter
{
protected $tokenizer;

public function __construct(TokenizerInterface $tokenizer = null)
{
$this->tokenizer = $tokenizer ?: new Tokenizer;
}

public function highlight($text, $query, $tag = 'em')
{
$terms = $this->tokenizer->tokenize($query);

$patterns = array_map(function ($term) {
return "/{$term}/is";
}, array_unique($terms));

$replacement = "<{$tag}>\$0</{$tag}>";

return preg_replace($patterns, $replacement, $text);
}

public function getTokenizer()
{
return $this->tokenizer;
}
}

0 comments on commit 3331ccf

Please sign in to comment.