PHP:列出找到单词的次数?

Joh*_*ohn 1 php iteration performance logging

我有一个自定义日志,大约29MB的用户数据,包括用户代理.我想通过它进行解析(基本上只是搜索),并找出有多少出现,"Firefox"或"MSIE"出现在其中,就像一个迷你日志解析器.

这是我难倒的地方..我得到的是explode()新行,并遍历数组,使用:

if stripos($line, 'Firefox') $ff++;" 
Run Code Online (Sandbox Code Playgroud)

或者是愚蠢的东西,但我意识到会占用大量内存/使用很多功能.

列出出现次数的好方法是什么?

Nul*_*ion 5

您需要逐行读取文件以避免耗尽大量数据的内存.

$count = array('Firefox' => 0, 'MSIE' => 0, 'Others' => 0);
$handle = fopen("yourfile", "r");

if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);

        // actual counting here:
        if (stripos($buffer, 'Firefox')) {
            $count['Firefox']++;
        } else if (stripos($buffer, 'MSIE')) {
            $count['MSIE']++;

        // this might be irrelevant if not all your lines contain user-agent
        // strings, but is here to show the idea
        } else {
            $count['Others']++; 
        }
    }
    fclose($handle);
}

print_r($count);
Run Code Online (Sandbox Code Playgroud)

此外,根据您的文件格式(未提供),您可能需要使用正则表达式或更精确的方法来计算出现的次数,例如:

$count = array('Firefox' => 0, 'MSIE' => 0, 'Others' => 0);
$handle = fopen("yourfile", "r");

if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        $ua = get_user_agent($buffer);  
        $count[$ua]++;
    }
    fclose($handle);
}

print_r($count);

/* @param $line
 * @return string representing the user-agent
 *
 * strpos() works for the most part, but you can use something more 
 * accurate if you want
 */
function get_user_agent($line) {
    // implementation left as an exercise to the reader
}
Run Code Online (Sandbox Code Playgroud)