0

我是 PHP 的菜鸟。我有 PHP 脚本来搜索 CSV 文件。如何添加搜索过滤器最少 x 个字符,否则它会显示错误消息?

<?php
if ( !empty ( $_GET['search'] ) ) {
$search = mb_strtolower($_GET['search']);
$lines = file('file.csv');

$found = false;

foreach($lines as $line)
{
    $line = mb_strtolower($line);

    if(strpos($line, $search) !== false)
    {
        $line = explode(',', $line);

$found = true;
        $str = $line[0];
        $str = strtoupper($str);
        echo "<div class='datagrid'><table><thead><tr><th>MODEL</th><th width='50px;'>QUANTITY</th><th width='155px;'>MAIL</th></tr></thead><tbody><tr>";
        echo "<td style='font-weight:bold;'>" . $str; echo "</td>";
        echo "<td>" . $line[1]; echo "</td>";
        echo "<td><a href='mailto:mailaddress?subject=$str' id='button'>Send</a></td>";
        echo "</tr>";
        echo "</tbody></table></div>";
    }
}

if(!$found) {
    echo 'Nothing found.';
}
}
?>
4

1 回答 1

0

您可以使用 strlen 函数知道搜索词有多少个字符

http://php.net/manual/en/function.strlen.php

<?php
$search_min_len = 3;//Change this to your needs
if ( !empty ( $_GET['search'] ) ) {
    $search = mb_strtolower($_GET['search']);
    if(strlen($search ) >= $search_min_len) 
    {
        $lines = file('file.csv');

        $found = false;

        foreach($lines as $line)
        {
            $line = mb_strtolower($line);

            if(strpos($line, $search) !== false)
            {
                $line = explode(',', $line);

        $found = true;
                $str = $line[0];
                $str = strtoupper($str);
                echo "<div class='datagrid'><table><thead><tr><th>MODEL</th><th width='50px;'>QUANTITY</th><th width='155px;'>MAIL</th></tr></thead><tbody><tr>";
                echo "<td style='font-weight:bold;'>" . $str; echo "</td>";
                echo "<td>" . $line[1]; echo "</td>";
                echo "<td><a href='mailto:mailaddress?subject=$str' id='button'>Send</a></td>";
                echo "</tr>";
                echo "</tbody></table></div>";
            }
        }

        if(!$found) {
            echo 'Nothing found.';
        }
    }
    else 
    {
        echo 'Minimum '.$search_min_len.' characters error';
    }
}
?>

希望能帮助到你

于 2013-10-16T09:45:45.513 回答