Note that there are some explanatory texts on larger screens.

plurals
  1. POFilter a csv file by a word or text using php
    text
    copied!<p>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:</p> <pre><code>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" </code></pre> <p>I would like to filter by the third column. For example, if I filter by "wii" I will get rows 1 and 6 sent back:</p> <pre><code>Tom, 8, "football, soccer, baseball, wii, star wars, books" Tim, 9, "football, baseball, basketball, wii, cartoons" </code></pre> <p>If I filter by "wii" or "guitar" I will get rows 1, 4, and 6 sent back.</p> <pre><code>Tom, 8, "football, soccer, baseball, wii, star wars, books" Mike, 8, "basketball, music, guitar, cartoons, books" Tim, 9, "football, baseball, basketball, wii, cartoons" </code></pre> <p>I'm not good at php and arrays, but I've tried messing around with preg_match - but not sure if something like strpos is better. Here's what I've done but can't get it to work right:</p> <pre><code>&lt;?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 . "&lt;br&gt; \n"; } else { echo "A match was not found.&lt;br&gt; \n"; }} ?&gt; </code></pre> <p>Any coding help is appreciated. It would also be nice to have the search be case-insensitive. Thanks for reading!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload