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

Tho*_*mas 2 php csv text 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"
Run Code Online (Sandbox Code Playgroud)

我想按第三栏过滤.例如,如果我按"wii"过滤,我会收到第1行和第6行:

Tom, 8, "football, soccer, baseball, wii, star wars, books"
Tim, 9, "football, baseball, basketball, wii, cartoons"
Run Code Online (Sandbox Code Playgroud)

如果我按"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"
Run Code Online (Sandbox Code Playgroud)

我不擅长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";
}}
?>
Run Code Online (Sandbox Code Playgroud)

任何编码帮助表示赞赏.使搜索不区分大小写也很好.谢谢阅读!

Tat*_*nen 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";
    }
}
Run Code Online (Sandbox Code Playgroud)