I need to find out if a certain string is found in a CSV file in PHP. The string may be found in any of the fields in my CSV list.
CSV list is like:
"John Doe", "john.doe@gmail.com", "other information", "0800-0880880", "still some info"
"Other John", "other information"
etc, so that the lines in my CSV do not contain the same information.
I want to know if the any of the strings are found in any of the fields anyway.
This is what I’ve tried (and yes, I’m pretty bad at PHP):
<?php
$file_handle = fopen("csv.txt", "r");
$words = array('john', 'john.doe@gmail.com');
$words = array_map('preg_quote', $words);
$regex = '/'.implode('|', $words).'/i';
while (($line = fgetcsv($file_handle)) !== FALSE) {
list($name, $age, $hobbies) = $line;
if(in_array($regex, $line)) {
echo "found";
}
}
However, this doesnt echo anything.
Instead of reinventing the wheel use the
fgetcsv()function. https://www.php.net/manual/en/function.fgetcsv.phpOnce you have your data use
in_array()to see if each line has your search data.in_array()does not use a regex, it’s a string (not even a substring).