Skip to content

Commit

Permalink
Merge pull request #3344 from PHPOffice/Format-Masks_Improved-@
Browse files Browse the repository at this point in the history
Improved handling of @ format mask
  • Loading branch information
MarkBaker authored Feb 4, 2023
2 parents ad0b68c + edc003a commit 0f8f359
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/PhpSpreadsheet/Style/NumberFormat/Formatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@

class Formatter
{
private const SYMBOL_AT = '/@(?=(?:[^"]*"[^"]*")*[^"]*\Z)/miu';
private const SECTION_SPLIT = '/;(?=(?:[^"]*"[^"]*")*[^"]*\Z)/miu';

/**
* @param mixed $value
* @param mixed $val
Expand Down Expand Up @@ -112,7 +115,13 @@ public static function toFormattedString($value, $format, $callBack = null)
if (is_bool($value)) {
return $value ? Calculation::getTRUE() : Calculation::getFALSE();
}
// For now we do not treat strings although section 4 of a format code affects strings
// For now we do not treat strings in sections, although section 4 of a format code affects strings
// Process a single block format code containing @ for text substitution
if (preg_match(self::SECTION_SPLIT, $format) === 0 && preg_match(self::SYMBOL_AT, $format) === 1) {
return str_replace('"', '', preg_replace(self::SYMBOL_AT, (string) $value, $format) ?? '');
}

// If we have a text value, return it "as is"
if (!is_numeric($value)) {
return (string) $value;
}
Expand All @@ -138,7 +147,7 @@ function ($matches) {
$format = (string) preg_replace('/(\\\(((.)(?!((AM\/PM)|(A\/P))))|([^ ])))(?=(?:[^"]|"[^"]*")*$)/ui', '"${2}"', $format);

// Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal)
$sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format) ?: [];
$sections = preg_split(self::SECTION_SPLIT, $format) ?: [];

[$colors, $format, $value] = self::splitFormat($sections, $value);

Expand Down
21 changes: 21 additions & 0 deletions tests/data/Style/NumberFormat.php
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,27 @@
'test',
'_-€* #,##0.00_-;"-€"* #,##0.00_-;_-€* -??_-;_-@_-',
],
// String masks (ie. @)
[
'World',
'World',
'@',
],
[
'Hello World',
'World',
'Hello @',
],
[
'Hello World',
'World',
'"Hello "@',
],
[
'Meet me @ The Boathouse @ 16:30',
'The Boathouse',
'"Meet me @ "@" @ 16:30"',
],
// Named colours
// Simple color
[
Expand Down

0 comments on commit 0f8f359

Please sign in to comment.