• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPOffice / PhpSpreadsheet / 17369810423

01 Sep 2025 06:42AM UTC coverage: 95.124% (+0.01%) from 95.112%
17369810423

Pull #4618

github

web-flow
Merge 187cac789 into 8da69e5d6
Pull Request #4618: Option to Create Blank Sheet If LoadSheetsOnly Doesn't Find Any

24 of 24 new or added lines in 6 files covered. (100.0%)

4 existing lines in 1 file now uncovered.

40190 of 42250 relevant lines covered (95.12%)

346.97 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.19
/src/PhpSpreadsheet/Shared/StringHelper.php
1
<?php
2

3
namespace PhpOffice\PhpSpreadsheet\Shared;
4

5
use Composer\Pcre\Preg;
6
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
7
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
8
use Stringable;
9

10
class StringHelper
11
{
12
    private const CONTROL_CHARACTERS_KEYS = [
13
        "\x00",
14
        "\x01",
15
        "\x02",
16
        "\x03",
17
        "\x04",
18
        "\x05",
19
        "\x06",
20
        "\x07",
21
        "\x08",
22
        "\x0b",
23
        "\x0c",
24
        "\x0e",
25
        "\x0f",
26
        "\x10",
27
        "\x11",
28
        "\x12",
29
        "\x13",
30
        "\x14",
31
        "\x15",
32
        "\x16",
33
        "\x17",
34
        "\x18",
35
        "\x19",
36
        "\x1a",
37
        "\x1b",
38
        "\x1c",
39
        "\x1d",
40
        "\x1e",
41
        "\x1f",
42
    ];
43
    private const CONTROL_CHARACTERS_VALUES = [
44
        '_x0000_',
45
        '_x0001_',
46
        '_x0002_',
47
        '_x0003_',
48
        '_x0004_',
49
        '_x0005_',
50
        '_x0006_',
51
        '_x0007_',
52
        '_x0008_',
53
        '_x000B_',
54
        '_x000C_',
55
        '_x000E_',
56
        '_x000F_',
57
        '_x0010_',
58
        '_x0011_',
59
        '_x0012_',
60
        '_x0013_',
61
        '_x0014_',
62
        '_x0015_',
63
        '_x0016_',
64
        '_x0017_',
65
        '_x0018_',
66
        '_x0019_',
67
        '_x001A_',
68
        '_x001B_',
69
        '_x001C_',
70
        '_x001D_',
71
        '_x001E_',
72
        '_x001F_',
73
    ];
74

75
    /**
76
     * SYLK Characters array.
77
     */
78
    private const SYLK_CHARACTERS = [
79
        "\x1B 0" => "\x00",
80
        "\x1B 1" => "\x01",
81
        "\x1B 2" => "\x02",
82
        "\x1B 3" => "\x03",
83
        "\x1B 4" => "\x04",
84
        "\x1B 5" => "\x05",
85
        "\x1B 6" => "\x06",
86
        "\x1B 7" => "\x07",
87
        "\x1B 8" => "\x08",
88
        "\x1B 9" => "\x09",
89
        "\x1B :" => "\x0a",
90
        "\x1B ;" => "\x0b",
91
        "\x1B <" => "\x0c",
92
        "\x1B =" => "\x0d",
93
        "\x1B >" => "\x0e",
94
        "\x1B ?" => "\x0f",
95
        "\x1B!0" => "\x10",
96
        "\x1B!1" => "\x11",
97
        "\x1B!2" => "\x12",
98
        "\x1B!3" => "\x13",
99
        "\x1B!4" => "\x14",
100
        "\x1B!5" => "\x15",
101
        "\x1B!6" => "\x16",
102
        "\x1B!7" => "\x17",
103
        "\x1B!8" => "\x18",
104
        "\x1B!9" => "\x19",
105
        "\x1B!:" => "\x1a",
106
        "\x1B!;" => "\x1b",
107
        "\x1B!<" => "\x1c",
108
        "\x1B!=" => "\x1d",
109
        "\x1B!>" => "\x1e",
110
        "\x1B!?" => "\x1f",
111
        "\x1B'?" => "\x7f",
112
        "\x1B(0" => '€', // 128 in CP1252
113
        "\x1B(2" => '‚', // 130 in CP1252
114
        "\x1B(3" => 'ƒ', // 131 in CP1252
115
        "\x1B(4" => '„', // 132 in CP1252
116
        "\x1B(5" => '…', // 133 in CP1252
117
        "\x1B(6" => '†', // 134 in CP1252
118
        "\x1B(7" => '‡', // 135 in CP1252
119
        "\x1B(8" => 'ˆ', // 136 in CP1252
120
        "\x1B(9" => '‰', // 137 in CP1252
121
        "\x1B(:" => 'Š', // 138 in CP1252
122
        "\x1B(;" => '‹', // 139 in CP1252
123
        "\x1BNj" => 'Œ', // 140 in CP1252
124
        "\x1B(>" => 'Ž', // 142 in CP1252
125
        "\x1B)1" => '‘', // 145 in CP1252
126
        "\x1B)2" => '’', // 146 in CP1252
127
        "\x1B)3" => '“', // 147 in CP1252
128
        "\x1B)4" => '”', // 148 in CP1252
129
        "\x1B)5" => '•', // 149 in CP1252
130
        "\x1B)6" => '–', // 150 in CP1252
131
        "\x1B)7" => '—', // 151 in CP1252
132
        "\x1B)8" => '˜', // 152 in CP1252
133
        "\x1B)9" => '™', // 153 in CP1252
134
        "\x1B):" => 'š', // 154 in CP1252
135
        "\x1B);" => '›', // 155 in CP1252
136
        "\x1BNz" => 'œ', // 156 in CP1252
137
        "\x1B)>" => 'ž', // 158 in CP1252
138
        "\x1B)?" => 'Ÿ', // 159 in CP1252
139
        "\x1B*0" => ' ', // 160 in CP1252
140
        "\x1BN!" => '¡', // 161 in CP1252
141
        "\x1BN\"" => '¢', // 162 in CP1252
142
        "\x1BN#" => '£', // 163 in CP1252
143
        "\x1BN(" => '¤', // 164 in CP1252
144
        "\x1BN%" => '¥', // 165 in CP1252
145
        "\x1B*6" => '¦', // 166 in CP1252
146
        "\x1BN'" => '§', // 167 in CP1252
147
        "\x1BNH " => '¨', // 168 in CP1252
148
        "\x1BNS" => '©', // 169 in CP1252
149
        "\x1BNc" => 'ª', // 170 in CP1252
150
        "\x1BN+" => '«', // 171 in CP1252
151
        "\x1B*<" => '¬', // 172 in CP1252
152
        "\x1B*=" => '­', // 173 in CP1252
153
        "\x1BNR" => '®', // 174 in CP1252
154
        "\x1B*?" => '¯', // 175 in CP1252
155
        "\x1BN0" => '°', // 176 in CP1252
156
        "\x1BN1" => '±', // 177 in CP1252
157
        "\x1BN2" => '²', // 178 in CP1252
158
        "\x1BN3" => '³', // 179 in CP1252
159
        "\x1BNB " => '´', // 180 in CP1252
160
        "\x1BN5" => 'µ', // 181 in CP1252
161
        "\x1BN6" => '¶', // 182 in CP1252
162
        "\x1BN7" => '·', // 183 in CP1252
163
        "\x1B+8" => '¸', // 184 in CP1252
164
        "\x1BNQ" => '¹', // 185 in CP1252
165
        "\x1BNk" => 'º', // 186 in CP1252
166
        "\x1BN;" => '»', // 187 in CP1252
167
        "\x1BN<" => '¼', // 188 in CP1252
168
        "\x1BN=" => '½', // 189 in CP1252
169
        "\x1BN>" => '¾', // 190 in CP1252
170
        "\x1BN?" => '¿', // 191 in CP1252
171
        "\x1BNAA" => 'À', // 192 in CP1252
172
        "\x1BNBA" => 'Á', // 193 in CP1252
173
        "\x1BNCA" => 'Â', // 194 in CP1252
174
        "\x1BNDA" => 'Ã', // 195 in CP1252
175
        "\x1BNHA" => 'Ä', // 196 in CP1252
176
        "\x1BNJA" => 'Å', // 197 in CP1252
177
        "\x1BNa" => 'Æ', // 198 in CP1252
178
        "\x1BNKC" => 'Ç', // 199 in CP1252
179
        "\x1BNAE" => 'È', // 200 in CP1252
180
        "\x1BNBE" => 'É', // 201 in CP1252
181
        "\x1BNCE" => 'Ê', // 202 in CP1252
182
        "\x1BNHE" => 'Ë', // 203 in CP1252
183
        "\x1BNAI" => 'Ì', // 204 in CP1252
184
        "\x1BNBI" => 'Í', // 205 in CP1252
185
        "\x1BNCI" => 'Î', // 206 in CP1252
186
        "\x1BNHI" => 'Ï', // 207 in CP1252
187
        "\x1BNb" => 'Ð', // 208 in CP1252
188
        "\x1BNDN" => 'Ñ', // 209 in CP1252
189
        "\x1BNAO" => 'Ò', // 210 in CP1252
190
        "\x1BNBO" => 'Ó', // 211 in CP1252
191
        "\x1BNCO" => 'Ô', // 212 in CP1252
192
        "\x1BNDO" => 'Õ', // 213 in CP1252
193
        "\x1BNHO" => 'Ö', // 214 in CP1252
194
        "\x1B-7" => '×', // 215 in CP1252
195
        "\x1BNi" => 'Ø', // 216 in CP1252
196
        "\x1BNAU" => 'Ù', // 217 in CP1252
197
        "\x1BNBU" => 'Ú', // 218 in CP1252
198
        "\x1BNCU" => 'Û', // 219 in CP1252
199
        "\x1BNHU" => 'Ü', // 220 in CP1252
200
        "\x1B-=" => 'Ý', // 221 in CP1252
201
        "\x1BNl" => 'Þ', // 222 in CP1252
202
        "\x1BN{" => 'ß', // 223 in CP1252
203
        "\x1BNAa" => 'à', // 224 in CP1252
204
        "\x1BNBa" => 'á', // 225 in CP1252
205
        "\x1BNCa" => 'â', // 226 in CP1252
206
        "\x1BNDa" => 'ã', // 227 in CP1252
207
        "\x1BNHa" => 'ä', // 228 in CP1252
208
        "\x1BNJa" => 'å', // 229 in CP1252
209
        "\x1BNq" => 'æ', // 230 in CP1252
210
        "\x1BNKc" => 'ç', // 231 in CP1252
211
        "\x1BNAe" => 'è', // 232 in CP1252
212
        "\x1BNBe" => 'é', // 233 in CP1252
213
        "\x1BNCe" => 'ê', // 234 in CP1252
214
        "\x1BNHe" => 'ë', // 235 in CP1252
215
        "\x1BNAi" => 'ì', // 236 in CP1252
216
        "\x1BNBi" => 'í', // 237 in CP1252
217
        "\x1BNCi" => 'î', // 238 in CP1252
218
        "\x1BNHi" => 'ï', // 239 in CP1252
219
        "\x1BNs" => 'ð', // 240 in CP1252
220
        "\x1BNDn" => 'ñ', // 241 in CP1252
221
        "\x1BNAo" => 'ò', // 242 in CP1252
222
        "\x1BNBo" => 'ó', // 243 in CP1252
223
        "\x1BNCo" => 'ô', // 244 in CP1252
224
        "\x1BNDo" => 'õ', // 245 in CP1252
225
        "\x1BNHo" => 'ö', // 246 in CP1252
226
        "\x1B/7" => '÷', // 247 in CP1252
227
        "\x1BNy" => 'ø', // 248 in CP1252
228
        "\x1BNAu" => 'ù', // 249 in CP1252
229
        "\x1BNBu" => 'ú', // 250 in CP1252
230
        "\x1BNCu" => 'û', // 251 in CP1252
231
        "\x1BNHu" => 'ü', // 252 in CP1252
232
        "\x1B/=" => 'ý', // 253 in CP1252
233
        "\x1BN|" => 'þ', // 254 in CP1252
234
        "\x1BNHy" => 'ÿ', // 255 in CP1252
235
    ];
236

237
    /**
238
     * Decimal separator.
239
     */
240
    private static ?string $decimalSeparator = null;
241

242
    /**
243
     * Thousands separator.
244
     */
245
    private static ?string $thousandsSeparator = null;
246

247
    /**
248
     * Currency code.
249
     */
250
    private static ?string $currencyCode = null;
251

252
    /**
253
     * Is iconv extension avalable?
254
     */
255
    private static ?bool $isIconvEnabled = null;
256

257
    /**
258
     * iconv options.
259
     */
260
    private static string $iconvOptions = '//IGNORE//TRANSLIT';
261

262
    /**
263
     * Get whether iconv extension is available.
264
     */
265
    public static function getIsIconvEnabled(): bool
266
    {
267
        if (isset(self::$isIconvEnabled)) {
238✔
268
            return self::$isIconvEnabled;
238✔
269
        }
270

271
        // Assume no problems with iconv
272
        self::$isIconvEnabled = true;
76✔
273

274
        // Fail if iconv doesn't exist
275
        if (!function_exists('iconv')) {
76✔
UNCOV
276
            self::$isIconvEnabled = false;
×
277
        } elseif (!@iconv('UTF-8', 'UTF-16LE', 'x')) {
76✔
278
            // Sometimes iconv is not working, and e.g. iconv('UTF-8', 'UTF-16LE', 'x') just returns false,
UNCOV
279
            self::$isIconvEnabled = false;
×
280
        } elseif (defined('PHP_OS') && @stristr(PHP_OS, 'AIX') && defined('ICONV_IMPL') && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && defined('ICONV_VERSION') && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)) {
76✔
281
            // CUSTOM: IBM AIX iconv() does not work
282
            self::$isIconvEnabled = false;
×
283
        }
284

285
        // Deactivate iconv default options if they fail (as seen on IMB i)
286
        if (self::$isIconvEnabled && !@iconv('UTF-8', 'UTF-16LE' . self::$iconvOptions, 'x')) {
76✔
UNCOV
287
            self::$iconvOptions = '';
×
288
        }
289

290
        return self::$isIconvEnabled;
76✔
291
    }
292

293
    /**
294
     * Convert from OpenXML escaped control character to PHP control character.
295
     *
296
     * Excel 2007 team:
297
     * ----------------
298
     * That's correct, control characters are stored directly in the shared-strings table.
299
     * We do encode characters that cannot be represented in XML using the following escape sequence:
300
     * _xHHHH_ where H represents a hexadecimal character in the character's value...
301
     * So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
302
     * element or in the shared string <t> element.
303
     *
304
     * @param string $textValue Value to unescape
305
     */
306
    public static function controlCharacterOOXML2PHP(string $textValue): string
307
    {
308
        return str_replace(self::CONTROL_CHARACTERS_VALUES, self::CONTROL_CHARACTERS_KEYS, $textValue);
527✔
309
    }
310

311
    /**
312
     * Convert from PHP control character to OpenXML escaped control character.
313
     *
314
     * Excel 2007 team:
315
     * ----------------
316
     * That's correct, control characters are stored directly in the shared-strings table.
317
     * We do encode characters that cannot be represented in XML using the following escape sequence:
318
     * _xHHHH_ where H represents a hexadecimal character in the character's value...
319
     * So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
320
     * element or in the shared string <t> element.
321
     *
322
     * @param string $textValue Value to escape
323
     */
324
    public static function controlCharacterPHP2OOXML(string $textValue): string
325
    {
326
        return str_replace(self::CONTROL_CHARACTERS_KEYS, self::CONTROL_CHARACTERS_VALUES, $textValue);
282✔
327
    }
328

329
    /**
330
     * Try to sanitize UTF8, replacing invalid sequences with Unicode substitution characters.
331
     */
332
    public static function sanitizeUTF8(string $textValue): string
333
    {
334
        $textValue = str_replace(["\xef\xbf\xbe", "\xef\xbf\xbf"], "\xef\xbf\xbd", $textValue);
9,180✔
335
        $subst = mb_substitute_character(); // default is question mark
9,180✔
336
        mb_substitute_character(65533); // Unicode substitution character
9,180✔
337
        $returnValue = (string) mb_convert_encoding($textValue, 'UTF-8', 'UTF-8');
9,180✔
338
        mb_substitute_character($subst);
9,180✔
339

340
        return $returnValue;
9,180✔
341
    }
342

343
    /**
344
     * Check if a string contains UTF8 data.
345
     */
346
    public static function isUTF8(string $textValue): bool
347
    {
348
        return $textValue === self::sanitizeUTF8($textValue);
1✔
349
    }
350

351
    /**
352
     * Formats a numeric value as a string for output in various output writers forcing
353
     * point as decimal separator in case locale is other than English.
354
     */
355
    public static function formatNumber(float|int|string|null $numericValue): string
356
    {
357
        if (is_float($numericValue)) {
1,008✔
358
            return str_replace(',', '.', (string) $numericValue);
1,008✔
359
        }
360

361
        return (string) $numericValue;
98✔
362
    }
363

364
    /**
365
     * Converts a UTF-8 string into BIFF8 Unicode string data (8-bit string length)
366
     * Writes the string using uncompressed notation, no rich text, no Asian phonetics
367
     * If mbstring extension is not available, ASCII is assumed, and compressed notation is used
368
     * although this will give wrong results for non-ASCII strings
369
     * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
370
     *
371
     * @param string $textValue UTF-8 encoded string
372
     * @param array<int, array{strlen: int, fontidx: int}> $arrcRuns Details of rich text runs in $value
373
     */
374
    public static function UTF8toBIFF8UnicodeShort(string $textValue, array $arrcRuns = []): string
375
    {
376
        // character count
377
        $ln = self::countCharacters($textValue, 'UTF-8');
122✔
378
        // option flags
379
        if (empty($arrcRuns)) {
122✔
380
            $data = pack('CC', $ln, 0x0001);
122✔
381
            // characters
382
            $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
122✔
383
        } else {
384
            $data = pack('vC', $ln, 0x09);
13✔
385
            $data .= pack('v', count($arrcRuns));
13✔
386
            // characters
387
            $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
13✔
388
            foreach ($arrcRuns as $cRun) {
13✔
389
                $data .= pack('v', $cRun['strlen']);
13✔
390
                $data .= pack('v', $cRun['fontidx']);
13✔
391
            }
392
        }
393

394
        return $data;
122✔
395
    }
396

397
    /**
398
     * Converts a UTF-8 string into BIFF8 Unicode string data (16-bit string length)
399
     * Writes the string using uncompressed notation, no rich text, no Asian phonetics
400
     * If mbstring extension is not available, ASCII is assumed, and compressed notation is used
401
     * although this will give wrong results for non-ASCII strings
402
     * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
403
     *
404
     * @param string $textValue UTF-8 encoded string
405
     */
406
    public static function UTF8toBIFF8UnicodeLong(string $textValue): string
407
    {
408
        // characters
409
        $chars = self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
123✔
410
        $ln = (int) (strlen($chars) / 2);  // N.B. - strlen, not mb_strlen issue #642
123✔
411

412
        return pack('vC', $ln, 0x0001) . $chars;
123✔
413
    }
414

415
    /**
416
     * Convert string from one encoding to another.
417
     *
418
     * @param string $to Encoding to convert to, e.g. 'UTF-8'
419
     * @param string $from Encoding to convert from, e.g. 'UTF-16LE'
420
     */
421
    public static function convertEncoding(string $textValue, string $to, string $from): string
422
    {
423
        if (self::getIsIconvEnabled()) {
237✔
424
            $result = iconv($from, $to . self::$iconvOptions, $textValue);
237✔
425
            if (false !== $result) {
237✔
426
                return $result;
237✔
427
            }
428
        }
429

UNCOV
430
        return (string) mb_convert_encoding($textValue, $to, $from);
×
431
    }
432

433
    /**
434
     * Get character count.
435
     *
436
     * @param string $encoding Encoding
437
     *
438
     * @return int Character count
439
     */
440
    public static function countCharacters(string $textValue, string $encoding = 'UTF-8'): int
441
    {
442
        return mb_strlen($textValue, $encoding);
10,761✔
443
    }
444

445
    /**
446
     * Get character count using mb_strwidth rather than mb_strlen.
447
     *
448
     * @param string $encoding Encoding
449
     *
450
     * @return int Character count
451
     */
452
    public static function countCharactersDbcs(string $textValue, string $encoding = 'UTF-8'): int
453
    {
454
        return mb_strwidth($textValue, $encoding);
82✔
455
    }
456

457
    /**
458
     * Get a substring of a UTF-8 encoded string.
459
     *
460
     * @param string $textValue UTF-8 encoded string
461
     * @param int $offset Start offset
462
     * @param ?int $length Maximum number of characters in substring
463
     */
464
    public static function substring(string $textValue, int $offset, ?int $length = 0): string
465
    {
466
        return mb_substr($textValue, $offset, $length, 'UTF-8');
10,733✔
467
    }
468

469
    /**
470
     * Convert a UTF-8 encoded string to upper case.
471
     *
472
     * @param string $textValue UTF-8 encoded string
473
     */
474
    public static function strToUpper(string $textValue): string
475
    {
476
        return mb_convert_case($textValue, MB_CASE_UPPER, 'UTF-8');
10,522✔
477
    }
478

479
    /**
480
     * Convert a UTF-8 encoded string to lower case.
481
     *
482
     * @param string $textValue UTF-8 encoded string
483
     */
484
    public static function strToLower(string $textValue): string
485
    {
486
        return mb_convert_case($textValue, MB_CASE_LOWER, 'UTF-8');
10,215✔
487
    }
488

489
    /**
490
     * Convert a UTF-8 encoded string to title/proper case
491
     * (uppercase every first character in each word, lower case all other characters).
492
     *
493
     * @param string $textValue UTF-8 encoded string
494
     */
495
    public static function strToTitle(string $textValue): string
496
    {
497
        return mb_convert_case($textValue, MB_CASE_TITLE, 'UTF-8');
18✔
498
    }
499

500
    public static function mbIsUpper(string $character): bool
501
    {
502
        return mb_strtolower($character, 'UTF-8') !== $character;
21✔
503
    }
504

505
    /**
506
     * Splits a UTF-8 string into an array of individual characters.
507
     *
508
     * @return string[]
509
     */
510
    public static function mbStrSplit(string $string): array
511
    {
512
        // Split at all position not after the start: ^
513
        // and not before the end: $
514
        $split = Preg::split('/(?<!^)(?!$)/u', $string);
21✔
515

516
        return $split;
21✔
517
    }
518

519
    /**
520
     * Reverse the case of a string, so that all uppercase characters become lowercase
521
     * and all lowercase characters become uppercase.
522
     *
523
     * @param string $textValue UTF-8 encoded string
524
     */
525
    public static function strCaseReverse(string $textValue): string
526
    {
527
        $characters = self::mbStrSplit($textValue);
21✔
528
        foreach ($characters as &$character) {
21✔
529
            if (self::mbIsUpper($character)) {
21✔
530
                $character = mb_strtolower($character, 'UTF-8');
14✔
531
            } else {
532
                $character = mb_strtoupper($character, 'UTF-8');
17✔
533
            }
534
        }
535

536
        return implode('', $characters);
21✔
537
    }
538

539
    private static function useAlt(string $altValue, string $default, bool $trimAlt): string
540
    {
541
        return ($trimAlt ? trim($altValue) : $altValue) ?: $default;
1✔
542
    }
543

544
    private static function getLocaleValue(string $key, string $altKey, string $default, bool $trimAlt = false): string
545
    {
546
        /** @var string[] */
547
        $localeconv = localeconv();
145✔
548
        $rslt = $localeconv[$key];
145✔
549
        // win-1252 implements Euro as 0x80 plus other symbols
550
        // Not suitable for Composer\Pcre\Preg
551
        if (preg_match('//u', $rslt) !== 1) {
145✔
552
            $rslt = '';
1✔
553
        }
554

555
        return $rslt ?: self::useAlt($localeconv[$altKey], $default, $trimAlt);
145✔
556
    }
557

558
    /**
559
     * Get the decimal separator. If it has not yet been set explicitly, try to obtain number
560
     * formatting information from locale.
561
     */
562
    public static function getDecimalSeparator(): string
563
    {
564
        if (!isset(self::$decimalSeparator)) {
1,126✔
565
            self::$decimalSeparator = self::getLocaleValue('decimal_point', 'mon_decimal_point', '.');
133✔
566
        }
567

568
        return self::$decimalSeparator;
1,126✔
569
    }
570

571
    /**
572
     * Set the decimal separator. Only used by NumberFormat::toFormattedString()
573
     * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
574
     *
575
     * @param ?string $separator Character for decimal separator
576
     */
577
    public static function setDecimalSeparator(?string $separator): void
578
    {
579
        self::$decimalSeparator = $separator;
927✔
580
    }
581

582
    /**
583
     * Get the thousands separator. If it has not yet been set explicitly, try to obtain number
584
     * formatting information from locale.
585
     */
586
    public static function getThousandsSeparator(): string
587
    {
588
        if (!isset(self::$thousandsSeparator)) {
1,138✔
589
            self::$thousandsSeparator = self::getLocaleValue('thousands_sep', 'mon_thousands_sep', ',');
134✔
590
        }
591

592
        return self::$thousandsSeparator;
1,138✔
593
    }
594

595
    /**
596
     * Set the thousands separator. Only used by NumberFormat::toFormattedString()
597
     * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
598
     *
599
     * @param ?string $separator Character for thousands separator
600
     */
601
    public static function setThousandsSeparator(?string $separator): void
602
    {
603
        self::$thousandsSeparator = $separator;
927✔
604
    }
605

606
    /**
607
     *    Get the currency code. If it has not yet been set explicitly, try to obtain the
608
     *        symbol information from locale.
609
     */
610
    public static function getCurrencyCode(bool $trimAlt = false): string
611
    {
612
        if (!isset(self::$currencyCode)) {
78✔
613
            self::$currencyCode = self::getLocaleValue('currency_symbol', 'int_curr_symbol', '$', $trimAlt);
28✔
614
        }
615

616
        return self::$currencyCode;
78✔
617
    }
618

619
    /**
620
     * Set the currency code. Only used by NumberFormat::toFormattedString()
621
     *        to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
622
     *
623
     * @param ?string $currencyCode Character for currency code
624
     */
625
    public static function setCurrencyCode(?string $currencyCode): void
626
    {
627
        self::$currencyCode = $currencyCode;
925✔
628
    }
629

630
    /**
631
     * Convert SYLK encoded string to UTF-8.
632
     *
633
     * @param string $textValue SYLK encoded string
634
     *
635
     * @return string UTF-8 encoded string
636
     */
637
    public static function SYLKtoUTF8(string $textValue): string
638
    {
639
        // If there is no escape character in the string there is nothing to do
640
        if (!str_contains($textValue, "\x1b")) {
11✔
641
            return $textValue;
10✔
642
        }
643

644
        foreach (self::SYLK_CHARACTERS as $k => $v) {
3✔
645
            $textValue = str_replace($k, $v, $textValue);
3✔
646
        }
647

648
        return $textValue;
3✔
649
    }
650

651
    /**
652
     * Retrieve any leading numeric part of a string, or return the full string if no leading numeric
653
     * (handles basic integer or float, but not exponent or non decimal).
654
     *
655
     * @return float|string string or only the leading numeric part of the string
656
     */
657
    public static function testStringAsNumeric(string $textValue): float|string
658
    {
659
        if (is_numeric($textValue)) {
299✔
660
            return $textValue;
296✔
661
        }
662
        $v = (float) $textValue;
6✔
663

664
        return (is_numeric(substr($textValue, 0, strlen((string) $v)))) ? $v : $textValue;
6✔
665
    }
666

667
    public static function strlenAllowNull(?string $string): int
668
    {
669
        return strlen("$string");
39✔
670
    }
671

672
    /** @param bool $convertBool If true, convert bool to locale-aware TRUE/FALSE rather than 1/null-string */
673
    public static function convertToString(mixed $value, bool $throw = true, string $default = '', bool $convertBool = false): string
674
    {
675
        if ($convertBool && is_bool($value)) {
14,300✔
676
            return $value ? Calculation::getTRUE() : Calculation::getFALSE();
3✔
677
        }
678
        if (is_float($value)) {
14,300✔
679
            $string = (string) $value;
4,700✔
680
            // look out for scientific notation
681
            if (!Preg::isMatch('/[^-+0-9.]/', $string)) {
4,700✔
682
                $minus = $value < 0 ? '-' : '';
4,673✔
683
                $positive = abs($value);
4,673✔
684
                $floor = floor($positive);
4,673✔
685
                $oldFrac = (string) ($positive - $floor);
4,673✔
686
                $frac = Preg::replace('/^0[.](\d+)$/', '$1', $oldFrac);
4,673✔
687
                if ($frac !== $oldFrac) {
4,673✔
688
                    return "$minus$floor.$frac";
4,504✔
689
                }
690
            }
691

692
            return $string;
420✔
693
        }
694
        if ($value === null || is_scalar($value) || $value instanceof Stringable) {
14,296✔
695
            return (string) $value;
14,292✔
696
        }
697

698
        if ($throw) {
5✔
699
            throw new SpreadsheetException('Unable to convert to string');
5✔
700
        }
701

702
        return $default;
1✔
703
    }
704

705
    /**
706
     * Assist with POST items when samples are run in browser.
707
     * Never run as part of unit tests, which are command line.
708
     *
709
     * @codeCoverageIgnore
710
     */
711
    public static function convertPostToString(string $index, string $default = ''): string
712
    {
713
        if (isset($_POST[$index])) {
714
            return htmlentities(self::convertToString($_POST[$index], false, $default));
715
        }
716

717
        return $default;
718
    }
719

720
    /**
721
     * Php introduced str_increment with Php8.3,
722
     * but didn't issue deprecation notices till 8.5.
723
     *
724
     * @codeCoverageIgnore
725
     */
726
    public static function stringIncrement(string &$str): string
727
    {
728
        if (function_exists('str_increment')) {
729
            $str = str_increment($str); // @phpstan-ignore-line
730
        } else {
731
            ++$str; // @phpstan-ignore-line
732
        }
733

734
        return $str; // @phpstan-ignore-line
735
    }
736
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc