【问题标题】:PHP preg_split search misses first wordPHP preg_split 搜索丢失第一个单词
【发布时间】:2013-11-19 01:27:48
【问题描述】:

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

例如,如果有一个名为“phone blue”的项目,我搜索“phone random”我什么也得不到,但是如果我搜索“random phone”(或“something ph”、“something phone random”,等)它找到“手机蓝色”。

我四处寻找不同的表达方式并尝试了它们(例如 @[\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而不是正常的explode函数?
  • 您能解释一下$tryagain 变量的含义吗?

标签: php regex database explode preg-split


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多