PHP wordwrap Function: Syntax, Parameters, Return Value, and Practical Examples

This article explains PHP's wordwrap() function, detailing its syntax, parameter meanings, return value, and providing three illustrative code examples that show how to wrap strings with custom line widths, break strings, and control word splitting.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP wordwrap Function: Syntax, Parameters, Return Value, and Practical Examples

This article introduces PHP’s built‑in wordwrap() function, which breaks a string into chunks of a specified width.

Syntax:

string wordwrap ( string $str , int $width = 75 , string $break = "
" , bool $cut = false )

.

The function splits the input string into lines of length $width. The optional $break string is inserted at each break point. If $cut is true, words longer than $width are split; otherwise they remain intact.

Parameters: $str – the input string. $width – the desired line width. $break – the string to insert at each break (default "\n"). $cut – boolean that determines whether long words are cut (true) or kept whole (false).

Return value: the wrapped string.

Example 1 – basic usage (width 20, break " \n"):

<?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.

Example 2 – force splitting of long words (cut = true):

<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "
", true);
echo $newtext;
?>

Output:

A very
long
wooooooo
oord.

Example 3 – keep long words intact (cut = false):

<?php
$text = "A very long wooooooooooooooooord. and something";
$newtext = wordwrap($text, 8, "
", false);
echo $newtext;
?>

Output:

A very
long
woooooooooooooooooord. and
something
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendStringtext processingexamplewordwrap
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.