php计算目录和子目录中文件的总字符串数

时间:2016-08-21 23:13:54

标签: php for-loop foreach count preg-match

我在目录和子目录中有多个文件。 文件标准如下

users.text examples

F: khkgjg1 3hs6q7a5x { expire=2016-08-21 13; afexpire=2017-08-20; email=kgtugh@kkk.com; Country=United State; country_code=US; hosted=none }
F: khkgjg2 hjfg545gh { expire=2016-09-21 13; afexpire=2017-08-20; email=kgtugh@kkk.com; Country=United State; country_code=US; hosted=none }
F: khkgjg3 hgdghgfh5 { expire=2017-08-21 13; afexpire=2017-08-20; email=kgtugh@kkk.com; Country=Duchland; country_code=DE; hosted=none }
F: khkgjg4 y5dhgfdh5 { expire=2015-08-21 13; afexpire=2017-08-20; email=kgtugh@kkk.com; Country=United State; country_code=US; hosted=none }

我有以下代码,我希望它计算具有此字符串的总行数 " country_code = US"在所有txt或cfg文件中。

<?php
$path_to_check  = '/path/phpm/linessysf/test/';
$types_to_check = "{*,ap/*}.{txt,cfg}";
$countrycd = "US";

foreach (glob($path_to_check . $types_to_check, GLOB_BRACE) as $filename) {
    foreach ($rows = file($filename) as $key => $row) {

        if (preg_match("#^F:.*?country_code=($countrycd);#is", $row, $valuesf)) {

        }
    }
}
echo $count_country;

我试着这样做但是我跌倒了,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您可以在preg_match之后添加计数器增量:

if (preg_match("#\bcountry_code=$countrycd\b;#is", $row)) {
    $count_country++;
}