PHP搜索CSV文件。搜索过滤最小字符

时间:2013-10-16 09:26:31

标签: php search csv

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

1 个答案:

答案 0 :(得分: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';
    }
}
?>

希望有所帮助