使用php通过单词或文本过滤csv文件 [英] Filter a csv file by a word or text using php

查看:205
本文介绍了使用php通过单词或文本过滤csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有另一个csv文件,我想做一个简单的字过滤器。例如,我的text.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"

我想通过第三列过滤。例如,如果我按wii过滤,我会得到第1和6行返回:

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"

如果我用wii或吉他过滤,我将得到第1,4和6行。

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"

和数组,但我试图搞砸preg_match - 但不知道如果像strpos是更好。这是我做的,但不能让它正常工作:

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> \n";
} else {
    echo "A match was not found.<br> \n";
}}
?>

任何编码帮助是值得赞赏的。

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

推荐答案

您可以接近,这样应该可以工作:

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 />\n";
    }
}

这篇关于使用php通过单词或文本过滤csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆