当搜索词是包含空格的字符串时,如何在数据库中搜索


How to search in database when the search term is a string that includes spaces?

我有这个字符串"Beautiful sunset"(注意双空格)

当我在数据库中搜索时:

SELECT * FROM images WHERE title LIKE '%$string%'

并且我搜索CCD_ 3(注意单个空格),它不会返回任何结果。

我该如何应对?

按空格分隔字符串。现在有两个字符串,类似于$str1和$str2修剪这两个字符串(即删除前导和尾随空格)然后重新生成字符串$string=$str1+"%"+$str2

试试这个

SELECT * FROM images WHERE where MATCH(title) AGAINST ('$string' IN BOOLEAN MODE)

同时检查此链接

http://dev.mysql.com/doc/refman/5.5/en/fulltext-boolean.html

您可以使用空格将搜索字符串拆分为多个部分,然后为拆分的每个部分构建这样的sql:

SELECT * FROM images WHERE title LIKE '%$part[0]%' 
or title LIKE '%$part[1]%'
or title LIKE '%$part[2]%'
or title LIKE '%$part[3]%'
...

确保跳过双空格/空部分。

实现这一点的一种方法是使用字符串替换来用通配符替换空格:

    $string = str_replace(" ", "%", $string);
    $Query  = "SELECT * FROM images WHERE title LIKE '%$string%'";

如果你不知道要得到什么字符串(如果不是一直都是"美丽的日落"),你可以分解字符串并根据它进行查询。就像这样…

$c = false;
$stringtosearch = "Beautiful sunset";
$query = "SELECT * FROM images WHERE";
foreach(explode(" ", $stringtosearch) as $b)
{
   if ($c)
   {
     $query .= " or";
   }
   $query .= " title LIKE " . $b;
   $c = true;
}

然后,您将获得带有查询字符串的变量$query。