PHP 布尔搜索


PHP boolean search

我正在尝试将用户输入的字符串转换为MySQL布尔搜索。 我有以下函数,它非常适合多种情况,但它不适用于双引号。

例如,它适用于以下字符串:

字符串 1:技术不是经理字符串 2:技术或经理或管理员

现在唯一不起作用的是当您输入用双引号括起来的短语时。 例如:

String3(不起作用):"技术作家"而不是"文档管理器"

这是我正在使用的功能:

function booltostring($input)
{
    $input = strtolower($input);
    $out = "";
    $plusflag = false;
    $minusflag = false;
    $forms = preg_split("%(and|or|not)%",$input,-1,PREG_SPLIT_DELIM_CAPTURE);
    $forms = array_map('trim',$forms);
    for($i = 0; $i < count($forms); $i++) 
    {
        switch($forms[$i]) 
        {
            case 'and':
                $plusflag = true;
                $minusflag = false;
                if(count(explode(' ',$forms[$i+1])) > 1) 
                {
                    $out .= '"+'.$forms[$i+1].'" ';
                } 
                else 
                {
                    $out .= "+".$forms[$i+1]." ";
                }
                $i++;
            break;
            case 'or':
                if(strpos($forms[$i-1],'OR')>-1 || strpos($forms[$i-1],'or')>-1)
                {
                    $plusflag = true;
                }
                if(count(explode(' ',$forms[$i+1])) > 1) 
                {
                    $out .= '"'.(($minusflag) ? "-" : "").$forms[$i+1].'" ';
                } 
                else 
                {
                    $out .= (($minusflag) ? "-" : "").$forms[$i+1]." ";
                }
                $i++;
            break;
            case 'not':
                $plusflag = false;
                $minusflag = true;
                if(count(explode(' ',$forms[$i+1])) > 1) 
                {
                    $out .= '"-'.$forms[$i+1].'" ';
                } 
                else 
                {
                    $out .= "-".$forms[$i+1]." ";
                }
                $i++;
            break;
            default:
                if(strpos($forms[$i+1],'OR')>-1 || strpos($forms[$i+1],'or')>-1)
                {
                    $plusflag = false;
                }
                if(strpos($forms[$i+1],'AND')>-1 || strpos($forms[$i+1],'and')>-1)
                {
                    $plusflag = true;
                }
                if(count(explode(' ',$forms[$i])) > 1) 
                {
                    $out .= (($plusflag) ? "+" : "")."'"".$forms[$i]."'" ";
                }
                else
                {
                    $out .= (($plusflag) ? "+" : "").$forms[$i]." ";
                }
            break;
      }
    }
    $out = trim($out);
    return $out;
}
"technical writer" not "document manager"

此字符串不起作用,因为您没有从字符串中删除双引号

使用trim函数删除它们

编辑

使用TRIM 关于个人值,即"技术作家"、"文档管理器"

像这样trim('"document manager"','"');

您只需要删除手动添加的双引号,然后应该没有问题。

比如这个

$out .= '"+'.$forms[$i+1].'" ';

因为这些双引号已经在输入字符串中