解析文本,分配变量,更新变量

时间:2013-12-05 17:00:33

标签: php regex

我希望获取一些文本文件,解析它们,找到一个正则表达式后面的最大数字并将其放入变量中。

这是我到目前为止所做的:

$txt_file = file_get_contents('files/11042013_300_active_users.log');
$rows = explode("\n", $txt_file);

$array_size = sizeof($rows);

for($i=0; $i < $array_size; $i++){
    echo $rows[$i];
    echo "<br />";
}

$max_user = 0;

for($i=0; $i < $array_size; $i++){
    if(preg_match("cnt=", $rows[$i])){
        $max_user++;
    }

}

echo $max_user;

我想查看的文件是常规文本文件。以下是内部示例:

11/04/13 07:51:14 +=+=+=+=+=+=+=+= total cnt=1
11/04/13 08:06:14 +=+=+=+=+=+=+=+= total cnt=1
11/04/13 08:21:14 +=+=+=+=+=+=+=+= total cnt=1
11/04/13 08:36:14 +=+=+=+=+=+=+=+= total cnt=1
11/04/13 08:51:14 +=+=+=+=+=+=+=+= total cnt=2
11/04/13 09:06:14 +=+=+=+=+=+=+=+= total cnt=5
11/04/13 09:21:14 +=+=+=+=+=+=+=+= total cnt=5
11/04/13 09:36:14 +=+=+=+=+=+=+=+= total cnt=2
11/04/13 09:51:14 +=+=+=+=+=+=+=+= total cnt=2

我感兴趣的是找到每行“cnt =”之后的最大整数。

根据我上面的代码,我为$ max_users持续获得0。我不相信我正确使用preg_match函数。

使用基于正则表达式(“cnt =”)搜索数组的最佳函数是什么,并且直接获取(整数)之后的函数?

2 个答案:

答案 0 :(得分:3)

非常简单的改变:

if(preg_match("/cnt=(\d+)$/", $rows[$i], $matches)){
    if ($matches[1] > $max_user) {
       $max_user = $matches[1];
    }
}

cnt之后捕获数字,并跟踪哪一个最大。

答案 1 :(得分:1)

这可以在不使用正则表达式的情况下轻松完成。您可以使用strpos()查找cnt=字符串的位置,然后使用substr()获取其后的所有内容(在这种情况下,就是您想要的内容),并将值添加到数组。一旦循环完成执行,您只需使用max()函数从数组中获取最大值。

$values = array();
for($i=0; $i < $array_size; $i++){
    // 4 is the length of the string 'cnt='
    $values[] = (int) substr($rows[$i], strpos($rows[$i], 'cnt=') + 4);
}

$max_user = max($values); // get the largest value from the array
echo $max_user; // => 5

现在,回答你原来的问题:

  

根据我上面的代码,我为$ max_users持续获得0。我不相信我正在使用preg_match函数正确

你不是。正则表达式需要包装在有效的分隔符中,并且代码中没有正则表达式。此外,即使有一个,它也行不通,因为你只检查该行是否包含cnt=字符串 - 在这种情况下对于所有行都是如此。

您需要在正则表达式中使用捕获组。例如:

if (preg_match("/cnt=(\d+)$/", $rows[$i], $matches)) {
    // $matches[1] contains only what's captured by the first parenthesis
    // which in this case, is the digit after 'cnt='

    // code to store the result in a variable and do the processing ...
}
相关问题