0

我有以下 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>";
4

3 回答 3

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%'";
}
于 2012-07-11T07:53:21.707 回答
0

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

改变这个——

foreach($search_exploded as $search_each) {

对此——

for($i = 0; $i < min(count($search_exploded), 4); ++$i) {
    $search_each = $search_exploded[$i];
于 2012-07-11T07:27:58.783 回答
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 个字符。

于 2012-07-11T07:44:42.597 回答