php / mysql计算搜索词和结果与关键字限制

时间:2012-07-11 07:22:14

标签: php mysql search count

我有以下PHP搜索脚本 当我搜索1234567时,它会匹配完整的词组,但我希望它只匹配最初的4个字符,即1234

解释

我希望它计算最初的4个字符,并显示与初始字符匹配的结果。例如。如果有人搜索1234567,则脚本应计算最初的4个字符,即1234并显示结果。同样,如果有人搜索456789,则脚本应计算最初的4个字符,即4567,并显示结果。

///explode search term
           $search_exploded = explode(" ",$search);
           foreach($search_exploded as  $search_each)
           {
           //construct query

            $x++;
            if ($x==1)
               $construct .= "keywords LIKE '%$search_each%'";
           else
              $construct .= " OR keywords LIKE '%$search_each%'";

           }


     //echo out construct

    $construct = "SELECT * FROM numbers WHERE $construct";
     $run = mysql_query($construct);

     $foundnum = mysql_num_rows($run);

     if ($foundnum==0)
        echo "No results found.";
     {

       echo "$foundnum results found.<p><hr size='1'>";

       while ($runrows = mysql_fetch_assoc($run))
       {
        //get data
        $title = $runrows['title']; 
        $desc = $runrows['description'];
       $url = $runrows['url'];

        echo "<b>$title</b>
             <b>$desc</b>
       <a href='$url'>$url</a><p>";

3 个答案:

答案 0 :(得分:1)

您可以将foreach替换为:

foreach($search_exploded as $search_each)
{
    $str = mysql_real_escape_string(substr($search_each, 0, 4));
    //construct query
    $x++;
    if ($x==1) $construct .= "keywords LIKE '$str%'";
    else       $construct .= " OR keywords LIKE '$str%'";
}

答案 1 :(得分:0)

要将现有代码修改为仅使用前4个单词,您只需稍微更改循环:

改变这个 -

foreach($search_exploded as $search_each) {

对此 -

for($i = 0; $i < min(count($search_exploded), 4); ++$i) {
    $search_each = $search_exploded[$i];

答案 2 :(得分:0)

将以下代码添加到foreach循环的顶部:

if(strlen($search_each) > 4) $search_each = substr($search_each, 0, 4);

像这样:

$search_exploded = explode(" ", $search);
foreach($search_exploded as $search_each)
{
    if(strlen($search_each) > 4) $search_each = substr($search_each, 0, 4);
    // your code
}

如果该单词长于4,则此代码将搜索每个单词中的前4个字符。