正则表达式解析/迭代

时间:2012-03-02 19:41:32

标签: php regex

如何遍历文件夹中的大约1,500个文本文件,每个文件包含

  

“完成率:119(isComplete:0)\ r \ n失败率:158 HC:   119-158-F“

得到“119”“0”“158”“119-158-F”了吗? 最简单的方法是什么?的preg_match?

3 个答案:

答案 0 :(得分:1)

使用preg_match_all()将每个匹配放入一个数组中。然后你可以print_r数组或内爆它。

// Define regex
$regex = '/[^0-9]*([0-9]+)[^0-9]*([0-9]+)[^0-9]*([0-9]+)[^0-9]*([0-9]+-[0-9]+-[A-Z]+)/s'; 

// Open the directory containing your 1500 files
if ($handle = opendir('/path/folder')) {

    // Loop over each file in the directory
    while (false !== ($entry = readdir($handle))) {

        // Open the file
        $file = file_get_contents($entry);

        // Use preg_match_all to store each value in an array
        preg_match_all($regex, $file, $numbers);

        $numbers = $numbers[0]; // yes you have to do this part

        print_r($numbers); // Or implode instead
        echo '<br />';

    }

    closedir($handle);
}

答案 1 :(得分:0)

我会使用glob迭代目录中的文本文件,如下所示,但还有其他选项,例如opendirreaddir ......

$myDir = '/path/to/text/files';

foreach (glob("$myDir/*.txt") as $filename) {
  $str = file_get_contents($myDir . '/' . $filename);
  $pattern = '/^\s*Completion rate: (\d+) \( isComplete: (\d) \)\s*Failure rate: (\d+) HC: ([A-Z0-9\-]+)\s*$/';
  if (preg_match($pattern, $str, $match)) {
    var_dump($match);
  }
}

答案 2 :(得分:0)

这对我来说很适合使用在线正则表达式测试器:

    preg_match_all('/[^0-9]*([0-9]+)[^0-9]*([0-9]+)[^0-9]*([0-9]+)[^0-9]*([0-9]+-[0-9]+-[A-Z]+)/s');

它会告诉你:

Array
(
[0] => Array
    (
        [0] => Completion rate: 129 ( isComplete: 0 )\r\nFailure rate: 158 HC: 119-158-F
    )

[1] => Array
    (
        [0] => 129
    )

[2] => Array
    (
        [0] => 0
    )

[3] => Array
    (
        [0] => 158
    )

[4] => Array
    (
        [0] => 119-158-F
    )

)