wordwrap() Function Use in PHP 8.4 and PHP 8.5

The wordwrap() function in PHP 8.4 and PHP 8.5 is fundamentally the same for everyday use. However, there is a specific bug fix regarding trailing line breaks that was merged into the PHP 8.5 branch, which differentiates its behavior from PHP 8.4 in edge cases.

Function

wordwrap() wraps a string to a given number of characters using a string break character. By default, it wraps at or before the specified width at a space character, and it does not split words unless you explicitly tell it to.

Signature:

wordwrap(
   string $string,
   int $width = 75,
   string $break = " ",
   bool $cut_long_words = false
): string

Key Behaviour:

→Default Wrapping: It looks for the last space before the $width limit and inserts the $break string there.
→Long Words: If $cut_long_words is false (default), a word longer than the width will not be broken and will exceed the line limit. If set to true, the function will force-break the long word at the width limit.
→Error Handling (Since PHP 8.0): If you pass an empty string as the $break parameter, it throws a Value Error.

Example

Here is a standard example of wrapping a sentence for HTML output:

<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br /> ");

echo $newtext;
?>

Output:

The quick brown fox<br />
jumped over the lazy<br />
dog.

This works identically in both PHP 8.4 and 8.5.

25 Views