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

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

任何编码帮助都会受到赞赏。如果搜索不区分大小写,那就太好了。感谢您的阅读!

最佳答案

你已经很接近了。像这样的东西应该有效:

$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 - 使用 php 按单词或文本过滤 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2382678/

相关文章:

PHP调用超父方法

php - 使用DirectAdmin编辑php.ini文件

php - MySQL - 选择并更新现有错误 0 值 (0000-00-00 00 :00:00) to Correct DateTime Values

text - 标记任何文本的最佳方法是什么?

php - 搜索 LONGTEXT 字段并显示结果

java - Spring内容协商/OpenCSV : Getting a blank CSV

excel - 如何在 Excel 加载项中保存用户首选项?

php - 值从 php 到存储过程

string - 对加密算法进行逆向工程

r - 检查 R 的连续捐赠年份