Skip to content

Commit 2f0b223

Browse files
committed
fix: keep long words whole in word_wrap() when charlim is 1
1 parent 9cd9ad3 commit 2f0b223

2 files changed

Lines changed: 8 additions & 12 deletions

File tree

‎system/Helpers/text_helper.php‎

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -386,26 +386,22 @@ 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-
393-
while (mb_strlen($line) > $charlim) {
389+
// A limit of 1 can't be used to split a word (each piece needs room for
390+
// the continuation), so the word is kept whole, like a long URL.
391+
while ($charlim > 1 && mb_strlen($line) > $charlim) {
394392
// If the over-length word is a URL we won't wrap it
395393
if (preg_match('!\[url.+\]|://|www\.!', $line)) {
396394
break;
397395
}
398-
// Trim the word down. Always take at least one character,
399-
// otherwise a limit of 1 or less would never make progress.
400-
$chunkLength = max(1, $charlim - 1);
401-
$temp .= mb_substr($line, 0, $chunkLength) . $separator;
402-
$line = mb_substr($line, $chunkLength);
396+
// Trim the word down
397+
$temp .= mb_substr($line, 0, $charlim - 1);
398+
$line = mb_substr($line, $charlim - 1);
403399
}
404400

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

‎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("a\na\na\na\nb\nb\nb\nb", word_wrap('aaaa bbbb', $charlim));
367+
$this->assertSame("aaaa\nbbbb", word_wrap('aaaa bbbb', $charlim));
368368
}
369369

370370
/**

0 commit comments

Comments
 (0)