PHP preg_split搜索会遗漏第一个单词


PHP preg_split search misses first word

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

例如,如果有一个名为"手机蓝色"的项目,我搜索"电话随机",

我什么也得不到,但是如果我搜索"随机电话"(或"某事 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;
    }

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

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

此链接通过示例更清晰:http://www.bakale.com/mysql/myfultext.htm