dowjgrm6787 2010-03-04 20:58
浏览 55
已采纳

使用php通过单词或文本过滤csv文件

I have another csv file where I am trying to do a simple word filter. For example, my text.csv file looks something like this:

name, age, hobbies
Tom, 8, "football, soccer, baseball, wii, star wars, books"
Bill, 9, "football, baseball, ice hockey, basketball"
Sue, 8, "baseball, soccer, volleyball, bicycles, skating"
Mike, 8, "basketball, music, guitar, cartoons, books"
Ella, 9, "soccer, basketball, softball, clothes, books"
Tim, 9, "football, baseball, basketball, wii, cartoons"
Steven, 8, "baseball, soccer, star wars, cartoons, books"

I would like to filter by the third column. For example, if I filter by "wii" I will get rows 1 and 6 sent back:

Tom, 8, "football, soccer, baseball, wii, star wars, books"
Tim, 9, "football, baseball, basketball, wii, cartoons"

If I filter by "wii" or "guitar" I will get rows 1, 4, and 6 sent back.

Tom, 8, "football, soccer, baseball, wii, star wars, books"
Mike, 8, "basketball, music, guitar, cartoons, books"
Tim, 9, "football, baseball, basketball, wii, cartoons"

I'm not good at php and arrays, but I've tried messing around with preg_match - but not sure if something like strpos is better. Here's what I've done but can't get it to work right:

<?PHP
$firstWord = 'wii';
$secondWord = 'guitar';
$file = fopen('text.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) 
{  
list($name[], $age[], $hobbies[]) = $line;
if (preg_match($firstWord, $hobbies[0]) || (preg_match($secondWord,     $hobbies[0]) {
echo $name . ',"' .$age . '",' .$hobbies . "<br> 
";
} else {
    echo "A match was not found.<br> 
";
}}
?>

Any coding help is appreciated. It would also be nice to have the search be case-insensitive. Thanks for reading!

  • 写回答

3条回答 默认 最新

  • doushenken2833 2010-03-04 21:04
    关注

    You're close. Something like this should work:

    $file  = fopen('text.csv', 'r');
    
    // You can use an array to store your search words, makes things more flexible.
    // Supports any number of search words.
    $words = array('wii', 'guitar');    
    // Make the search words safe to use in regex (escapes special characters)
    $words = array_map('preg_quote', $words);
    // The argument becomes '/wii|guitar/i', which means 'wii or guitar, case-insensitive'
    $regex = '/'.implode('|', $words).'/i';
    
    while (($line = fgetcsv($file)) !== FALSE) {  
        list($name, $age, $hobbies) = $line;
    
        if(preg_match($regex, $hobbies)) {
            echo "$name, $age, $hobbies<br />
    ";
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色