Skip to content

Commit 5cf4e2c

Browse files
committed
Fix handling for a # symbol in quotes inside a number format mask
1 parent ac11728 commit 5cf4e2c

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

src/PhpSpreadsheet/Style/NumberFormat/NumberFormatter.php

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -205,9 +205,6 @@ public static function format($value, string $format): string
205205
// return 'EUR ' . sprintf('%1.2f', $value);
206206
//}
207207

208-
// Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols
209-
$format = self::makeString(str_replace(['"', '*'], '', $format));
210-
211208
// Find out if we need thousands separator
212209
// This is indicated by a comma enclosed by a digit placeholder:
213210
// #,# or 0,0
@@ -229,20 +226,26 @@ public static function format($value, string $format): string
229226
$format = self::pregReplace('/0,+/', '0', $format);
230227
$format = self::pregReplace('/#,+/', '#', $format);
231228
}
229+
232230
if (preg_match('/#?.*\?\/(\?+|\d+)/', $format)) {
233231
$value = FractionFormatter::format($value, $format);
234232
} else {
235233
// Handle the number itself
236234

237235
// scale number
238236
$value = $value / $scale;
237+
239238
// Strip #
240-
$format = self::pregReplace('/\\#/', '0', $format);
239+
$format = self::pregReplace('/\\#(?=(?:[^"]*"[^"]*")*[^"]*\Z)/', '0', $format);
241240
// Remove locale code [$-###]
242241
$format = self::pregReplace('/\[\$\-.*\]/', '', $format);
243242

244243
$n = '/\\[[^\\]]+\\]/';
245244
$m = self::pregReplace($n, '', $format);
245+
246+
// Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols
247+
$format = self::makeString(str_replace(['"', '*'], '', $format));
248+
246249
if (preg_match(self::NUMBER_REGEX, $m, $matches)) {
247250
// There are placeholders for digits, so inject digits from the value into the mask
248251
$value = self::formatStraightNumericValue($value, $format, $matches, $useThousands);

tests/data/Style/NumberFormat.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1494,4 +1494,19 @@
14941494
-12345.6789,
14951495
'0.000E+00',
14961496
],
1497+
[
1498+
'Product SKU #12345',
1499+
12345,
1500+
'"Product SKU #"0',
1501+
],
1502+
[
1503+
'Product SKU #12-345',
1504+
12345,
1505+
'"Product SKU #"00-000',
1506+
],
1507+
[
1508+
'€12,345.74 Surplus for Product #12-345',
1509+
12345.74,
1510+
'[$€]#,##0.00" Surplus for Product #12-345";$-#,##0.00" Shortage for Product #12-345"',
1511+
],
14971512
];

0 commit comments

Comments
 (0)