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

时间:2010-03-04 20:58:48

标签: php text csv filter

我有另一个csv文件,我正在尝试做一个简单的文字过滤器。例如,我的text.csv文件看起来像这样:

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行发回:

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

如果我按“wii”或“吉他”过滤,我会将第1,4和6行送回。

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

我不擅长php和数组,但我已经尝试过使用preg_match - 但不确定strpos之类的东西是否更好。这就是我所做的,但无法让它正常工作:

<?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";
}}
?>

感谢任何编码帮助。使搜索不区分大小写也很好。谢谢你的阅读!

3 个答案:

答案 0 :(得分:6)

你很亲密。这样的事情应该有效:

$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";
    }
}

答案 1 :(得分:0)

不区分大小写的搜索怎么办?我很想将这个工作列在我的Outlook联系人列表中。是否有比strtolower()??

更好的使用功能

答案 2 :(得分:0)

这里值得注意的是PHP有CSV处理库。

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

这会将CSV的下一行作为数组返回,例如

// csv file contains "col1,col2,col3"
// array = {'col1', 'col2', 'col3'}
$array = fgetcsv($csv);

然后你可以简单地使用in_array()或$ array [column_number]上的测试进行过滤。

我不确定在线字符串上使用正则表达式而不是使用数组搜索功能会更快,所以它可能值得测试。