3v4l.org

run code in 300+ PHP versions simultaneously
<?php function extractPatterns(array $rules) : array { $postcodes = []; foreach ($rules as $rule) { if (preg_match('/^([A-Z]{1,2})([0-9]{1,2})-([0-9]{1,2})$/', trim($rule), $matches)) { for ($i = $matches[2]; $i <= $matches[3]; $i++) { $postcodes[] = sprintf('%s%s', $matches[1], $i); } continue; } if (preg_match('([A-Z]{1,2}[0-9]{1,2})', $rule, $matches)) { $postcodes[] = $matches[0]; continue; } if (preg_match('[A-Z]{1,2})', $rule, $matches)) { $postcodes[] = $matches[0]; continue; } } return $postcodes; } $tests = [ [ 'rules' => 'AB41-56, FK19-21, NG12', 'expected' => [ 'AB41', 'AB42', 'AB43', 'AB44', 'AB45', 'AB46', 'AB47', 'AB48', 'AB49', 'AB50', 'AB51', 'AB52', 'AB53', 'AB54', 'AB55', 'AB56', 'FK19', 'FK20', 'FK21', 'NG12' ] ], [ 'rules' => 'HU1, W1-5', 'expected' => [ 'HU1', 'W1', 'W2', 'W3', 'W4', 'W5' ] ] ]; foreach ($tests as $test) { assert(extractPatterns(explode(',', $test['rules'])) == $test['expected']); }

preferences:
38.72 ms | 402 KiB | 5 Q