问题
I have csv file "acct-2012-08-24-0001.csv" that contain many lines.I want to count all lines that contain the word "118-bonsplans.com" in line.But I do not know how to count it, I just can count all line in the csv file like the php code as below:
$word = "118-bonsplans.com";
$linecount = count(file('acct-2012-08-24-0001.csv'));
echo $linecount;
I do not know how to do continue.Anyone help me please, Thanks,
回答1:
How about:
count(preg_grep("/118\-bonsplans\.com/", file("acct-2012-08-24-0001.csv")));
The first argument to preg_grep is a regular expression pattern. The second is an array to search through. It returns an array of the items in the searched array that matched.
回答2:
You can try with the following code:
$handle = fopen('acct-2012-08-24-0001.csv', 'r');
$counter = 0;
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
if (stristr($buffer, '118-bonsplans.com')) $counter += 1;
}
fclose($handle);
}
echo $counter;
来源:https://stackoverflow.com/questions/12136000/count-line-that-contain-word-118-bonsplans-com-in-csv-file-using-php