Skip to content

Commit f28eea7

Browse files
ndenchMarkBaker
authored andcommitted
Use named regex groups and constants for regex strings
1 parent df01db5 commit f28eea7

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

src/PhpSpreadsheet/Cell/AddressHelper.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -102,20 +102,20 @@ public static function convertToR1C1(
102102
?int $currentRowNumber = null,
103103
?int $currentColumnNumber = null
104104
): string {
105-
$validityCheck = preg_match('/^(\$?)([A-Z]{1,3})(\$?)(\d{1,7})$/i', $address, $cellReference);
105+
$validityCheck = preg_match(Coordinate::A1_COORDINATE_REGEX, $address, $cellReference);
106106

107107
if ($validityCheck === 0) {
108108
throw new Exception('Invalid A1-format Cell Reference');
109109
}
110110

111-
$columnId = Coordinate::columnIndexFromString($cellReference[2]);
112-
if ($cellReference[1] === '$') {
111+
$columnId = Coordinate::columnIndexFromString($cellReference['col_ref']);
112+
if ($cellReference['absolute_col'] === '$') {
113113
// Column must be absolute address
114114
$currentColumnNumber = null;
115115
}
116116

117-
$rowId = (int) $cellReference[4];
118-
if ($cellReference[3] === '$') {
117+
$rowId = (int) $cellReference['row_ref'];
118+
if ($cellReference['absolute_row'] === '$') {
119119
// Row must be absolute address
120120
$currentRowNumber = null;
121121
}

src/PhpSpreadsheet/Cell/Coordinate.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
*/
1414
abstract class Coordinate
1515
{
16+
public const A1_COORDINATE_REGEX = '/^(?<absolute_col>\$?)(?<col_ref>[A-Z]{1,3})(?<absolute_row>\$?)(?<row_ref>\d{1,7})$/i';
17+
1618
/**
1719
* Default range variable constant.
1820
*
@@ -29,8 +31,8 @@ abstract class Coordinate
2931
*/
3032
public static function coordinateFromString($pCoordinateString)
3133
{
32-
if (preg_match('/^([$]?[A-Z]{1,3})([$]?\\d{1,7})$/', $pCoordinateString, $matches)) {
33-
return [$matches[1], $matches[2]];
34+
if (preg_match(self::A1_COORDINATE_REGEX, $pCoordinateString, $matches)) {
35+
return [$matches['absolute_col'] . $matches['col_ref'], $matches['absolute_row'] . $matches['row_ref']];
3436
} elseif (self::coordinateIsRange($pCoordinateString)) {
3537
throw new Exception('Cell coordinate string can not be a range of cells');
3638
} elseif ($pCoordinateString == '') {

0 commit comments

Comments
 (0)