Php MySql:like子句中的无序单词匹配

Php MySql:like子句中的无序单词匹配,php,mysql,Php,Mysql,如何实现名称匹配。类似“John S Smith”的内容必须与mysql数据库中的“Smith S”匹配。i、 e单词可以是无序的 是否可以在单个SQL查询中执行此操作?因为是名字,所以不会超过3个单词 我的代码在逻辑上不正确。任何帮助都将不胜感激 $words=explode(" ", $name); $sql="SELECT * FROM sent WHERE 1=1"; foreach ($words as $word) { $sql.=" AND customer_name

如何实现名称匹配。类似“John S Smith”的内容必须与mysql数据库中的“Smith S”匹配。i、 e单词可以是无序的

是否可以在单个SQL查询中执行此操作?因为是名字,所以不会超过3个单词

我的代码在逻辑上不正确。任何帮助都将不胜感激

$words=explode(" ", $name);

$sql="SELECT * FROM sent WHERE 1=1";

foreach ($words as $word)
{
    $sql.=" AND customer_name LIKE '%$word%'";
}
我得到的SQL如下所示

$sql="SELECT * FROM sent WHERE 1=1 AND customer_name LIKE '%John%' AND customer_name LIKE '%S%' AND customer_name LIKE '%Smith%'" ;

下面的代码将首先找到所有可能的单词组合,然后将其与数据库匹配 因为你的代码最多只有3个字,所以这不是一个坏的选择

    <?php
    $name ='John S Smith';
    $words=explode(" ", $name);;

    function get_all_combination($arr, $temp_string, &$collect) {
        if ($temp_string != "") 
            $collect []= $temp_string;

        for ($i=0; $i<sizeof($arr);$i++) {
            $arrcopy = $arr;
            $elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
            if (sizeof($arrcopy) > 0) {
                get_all_combination($arrcopy, $temp_string ." " . $elem[0], $collect);
            } else {
                $collect []= $temp_string. " " . $elem[0];
            }   
        }   
    }

    $collect = array();
    get_all_combination($words, "", $collect);

       /* 
        $collect now have 

        [0] =>  John
        [1] =>  John S
        [2] =>  John S Smith
        [3] =>  John Smith
        [4] =>  John Smith S
        [5] =>  S
        [6] =>  S John
        [7] =>  S John Smith
        [8] =>  S Smith
        [9] =>  S Smith John
        [10] =>  Smith
        [11] =>  Smith John
        [12] =>  Smith John S
        [13] =>  Smith S
        [14] =>  Smith S John 
        */

    $sql="SELECT * FROM sent WHERE 1=1 AND (customer_name = '".implode("' OR customer_name = '",$collect)."')" ;




    ?>

我认为您不需要分解名称,只需像select*from sent where customer_name那样“%.”$name.“%@abdulraziq“John S Smith”必须与“Smith John S”匹配您是否尝试了我向您展示的上述查询?生成的SQL有什么问题?看起来它会做你想让它做的事。我花了时间去做,所以请询问你是否需要帮助,这样我的努力就不会失败wasted@sanjeev谢谢你的努力:-)。我将在此基础上扩展我的代码。