PHP实现模糊搜索中文分词

1.下面代码复制到公共函数累里面

/**
 * 模糊搜索中文分词
 */
function decorateSearch_pre($words)
{
    $tempArr = str_split($words);
    $wordArr = array();
    $temp = '';
    $count = 0;
    $chineseLen = 3;
    foreach($tempArr as $word){
        if ($count == $chineseLen){
            $wordArr[] = $temp;
            $temp = '';
            $count = 0;
        }

        // 中文
        if(ord($word) > 127){
            $temp .= $word;
            ++$count;
        }else if (ord($word) != 32){
            $wordArr[] = $word;
        }
    }

    if ($count == $chineseLen){
        $wordArr[] = $temp;
    }

    return '%'.implode($wordArr, '%').'%';
}
2.ThinkPHP后台控制器调用实例:

    /**
     * 搜索功能
     */
    public function search() {
        //获取查找的内容
        $search = $_POST['text'];

        if($search) {
            $search = decorateSearch_pre($search);
            $map = [
                'content' => ['like', "%{$search}%"]
            ];

            //分页处理
            $count = M('ask')->where($map)->count('id');
            import('ORG.Util.Page');
            $page = new Page($count,15);
            $limit = $page->firstRow . ',' .$page->listRows;
            $this->result = D('AskView')->order('time DESC')->limit($limit)->where($map)->select();
            $this->page = $page->show();
            $this->display();
        } else {
            redirect($_SERVER['HTTP_REFERER']);
        }

    }




你可能感兴趣的:(PHP)