Skip to content

Commit 9cd9ad3

Browse files
committed
fix: wrap word_wrap() at one character when charlim is 1
1 parent 3542818 commit 9cd9ad3

2 files changed

Lines changed: 7 additions & 3 deletions

File tree

‎system/Helpers/text_helper.php‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,10 @@ function word_wrap(string $str, int $charlim = 76): string
386386

387387
$temp = '';
388388

389+
// Chunks are joined directly for wider limits, but with a limit of 1
390+
// each chunk is a full line of its own.
391+
$separator = $charlim === 1 ? "\n" : '';
392+
389393
while (mb_strlen($line) > $charlim) {
390394
// If the over-length word is a URL we won't wrap it
391395
if (preg_match('!\[url.+\]|://|www\.!', $line)) {
@@ -394,14 +398,14 @@ function word_wrap(string $str, int $charlim = 76): string
394398
// Trim the word down. Always take at least one character,
395399
// otherwise a limit of 1 or less would never make progress.
396400
$chunkLength = max(1, $charlim - 1);
397-
$temp .= mb_substr($line, 0, $chunkLength);
401+
$temp .= mb_substr($line, 0, $chunkLength) . $separator;
398402
$line = mb_substr($line, $chunkLength);
399403
}
400404

401405
// If $temp contains data it means we had to split up an over-length
402406
// word into smaller chunks so we'll add it back to our current line
403407
if ($temp !== '') {
404-
$output .= $temp . "\n" . $line . "\n";
408+
$output .= $temp . ($separator === '' ? "\n" : '') . $line . "\n";
405409
} else {
406410
$output .= $line . "\n";
407411
}

‎tests/system/Helpers/TextHelperTest.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ public function testEllipsize(): void
364364
#[DataProvider('provideWordWrapSmallCharLimit')]
365365
public function testWordWrapSmallCharLimit(int $charlim): void
366366
{
367-
$this->assertSame("aaa\na\nbbb\nb", word_wrap('aaaa bbbb', $charlim));
367+
$this->assertSame("a\na\na\na\nb\nb\nb\nb", word_wrap('aaaa bbbb', $charlim));
368368
}
369369

370370
/**

0 commit comments

Comments
 (0)