PHP preg_split搜索错过第一个单词

时间:2013-11-07 11:56:48

标签: php regex database explode preg-split

我正在使用preg_split来查找一些结果,除了(奇怪地)第一个单词外,它的效果很好。

例如,如果有一个名为“phone blue”的项目并且我搜索“手机随机”我什么都没得到,但是如果我搜索“随机手机”(或“某事ph”,“手机随机”,等)它找到“手机蓝”。

我一直在寻找不同的表达方式并尝试过它们(例如@ [\ W] + @,/ [\ s,] + /等)。但没有任何帮助。我只能假设第一次尝试找到该项目(使用完整的字符串)搞砸了,但不知道如何。对此非常新! 谢谢你的帮助

编辑:忘记注意只搜索“电话”也不起作用。

function find_by_location_or_name($where) {

    // first try complete
    $this->db->where('items_location', $where);
    $this->db->or_like('items_name', $where);
    $query = $this->db->from('items_table')->get();

    // if nothing, break it up, try again
    if( !$query->num_rows) {
        $where_like = preg_split('/ /',  $where);

        $tryagain = false;

        foreach($where_like as $like) {
            if(! $tryagain) {
                $this->db->like('items_location', $like);
            } else {
                $this->db->or_like('items_name', $like);
            }
            $tryagain = true;
        }

        // Do the query
        $query = $this->db->from('items_table')->get();
}

更新 谢谢大家的帮助!最终这有效:

// first try complete
$this->db->where('items_location', $where);
$this->db->or_where('items_name', $where);
$query = $this->db->from('items_table')->get();

// if nothing, break it up, try again
if( !$query->num_rows) {
    $where_like = preg_split('/ /',  $where);

    $tryagain = false;

    foreach($where_like as $like) {
        if(! $tryagain) {
            $this->db->like('items_location', $like);
            $this->db->or_like('items_name', $like);
        } else {
            $this->db->like('items_name', $like);
        }
        $tryagain = true;
    }

1 个答案:

答案 0 :(得分:0)

我看了你的代码。而不是preg_split你应该做全文索引并将整个字符串提供给MySQL。让MySQL找到它。这正是你所需要的。

请看: http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

此链接更清晰,有以下示例: http://www.bakale.com/mysql/myfultext.htm