【发布时间】: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