2011-11-06 23 views
0

我需要找出在PHP中是否在CSV文件中找到某個字符串。該字符串可以在我的CSV列表中的任何字段中找到。從CSV搜索數組

CSV名單是這樣的:

"John Doe", "[email protected]", "other information", "0800-0880880", "still some info" 
"Other John", "other information" 

等,所以,在我的CSV行不包含相同的信息。

我想知道是否任何字符串都可以在任何字段中找到。

這是我試過(是的,我很糟糕,在PHP):

<?php 
$file_handle = fopen("csv.txt", "r"); 
$words = array('john', '[email protected]'); 
$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"; 
} 
} 

然而,這並不回聲什麼。

回答

0

而不是重新發明車輪使用fgetcsv()函數。 http://us3.php.net/manual/en/function.fgetcsv.php

一旦你有你的數據使用in_array()看看每一行是否有你的搜索數據。

in_array()不使用正則表達式,它是一個字符串(甚至不是一個子字符串)。

0

嘗試更換while循環內(它已經使用getcsv()),像這樣的東西:

foreach ($line as $elt) { 
    if (preg_match($regex, $elt)) { 
     echo "found match in: " . $elt . "\n"; 
    } 
}