PHP 搜索 CSV 文件.搜索筛选最少字符数


PHP Search CSV file. Search filter minimum characters

我是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.';
}
}
?>

您可以使用 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';
    }
}
?>

希望对你有帮助