Search code examples
phpfor-loopforeachcountpreg-match

php count total string in files in directory and subdirectories


i have multiple files in directory and subdirectories. files standard as folowing

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 }

i have below code, i want it to count total lines that have this string "country_code= US" in all txt or cfg files.

<?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;

I tried to do that but i fall, can anyone help,please?


Solution

  • You can simply add the counter increment after the preg_match:

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