Skip to content

Commit

Permalink
Ignore cell formatting when the format is a single @
Browse files Browse the repository at this point in the history
This commit fix two issues that happened when the a cell was formatted as text
* When the cell contains a number prefixed with dollar sign, this number is getting replaced with 0. The replacement happens due to the preg_replace function.
* When the cell contains quotes, the quote would be removed.
  • Loading branch information
sirbaconjr committed Nov 26, 2024
1 parent fd562af commit 3eee749
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org).

### Fixed

- Nothing yet.
- Ignore cell formatting when the format is a single @. [Issue #4242](https://github.com/PHPOffice/PhpSpreadsheet/issues/4242) [PR #4243](https://github.com/PHPOffice/PhpSpreadsheet/pull/4243)

## 2024-11-22 - 3.5.0

Expand Down
8 changes: 7 additions & 1 deletion src/PhpSpreadsheet/Style/NumberFormat/Formatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,13 @@ public static function toFormattedString($value, string $format, ?array $callBac
// 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 (!str_contains($format, '"')) {
return str_replace('@', $value, $format);
}
//escape any dollar signs on the string, so they are not replaced with an empty value
$value = str_replace('$', '\\$', (string) $value);

return str_replace('"', '', preg_replace(self::SYMBOL_AT, $value, $format) ?? $value);
}

// If we have a text value, return it "as is"
Expand Down
20 changes: 20 additions & 0 deletions tests/data/Style/NumberFormat.php
Original file line number Diff line number Diff line change
Expand Up @@ -1682,4 +1682,24 @@
'#,##0.00;;"---"',
],
'issue 4124' => ['1 HUF', 1, '#,##0_-[$HUF]'],
'issue 4242-0' => [
'General $200 - 200', // expected result
'General $200 - 200', // cell contents
NumberFormat::FORMAT_GENERAL, // cell style
],
'issue 4242-1' => [
'Text $200 - 200',
'Text $200 - 200',
NumberFormat::FORMAT_TEXT,
],
'issue 4242-2' => [
'"Hello" she said and "Hello" I replied',
'"Hello" she said and "Hello" I replied',
NumberFormat::FORMAT_TEXT,
],
'issue 4242-3' => [
'Text: $200 - 200',
'$200 - 200',
'"Text: "' . NumberFormat::FORMAT_TEXT,
],
];

0 comments on commit 3eee749

Please sign in to comment.