Filter a csv file by a word or text using php

前端 未结 3 1371
猫巷女王i
猫巷女王i 2021-01-03 14:36

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, \"         


        
相关标签:
3条回答
  • 2021-01-03 15:02

    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";
        }
    }
    
    0 讨论(0)
  • 2021-01-03 15:07

    What about case insensitive searches. I'm curious to make this work amonst a list of my outlook contacts. Is there a better function to use than strtolower()??

    0 讨论(0)
  • 2021-01-03 15:08

    It's probably worth noting here that PHP has CSV handling libraries.

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

    This returns the next line of the CSV as an array e.g.

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

    Then you can simply use in_array() or a test on $array[column_number] to filter.

    I'm not sure if using a regular expression on the line string vs. using array search functions would be faster though, so it's probably worth testing.

    0 讨论(0)
提交回复
热议问题