gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:57:58 25 4
gpt4 key购买 nike

我有另一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com