Using PHP wordwrap() to Split Strings into Specified Lengths

This article explains the PHP wordwrap() function, its parameters (string, width, break, cut), return value, and provides two practical examples demonstrating how to break long strings into lines with custom delimiters and optional word cutting.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP wordwrap() to Split Strings into Specified Lengths

The wordwrap() function in PHP breaks a given string into smaller chunks based on a specified width, optional break string, and an optional cut flag that forces splitting even within words.

Parameters:

str : the input string to be wrapped.

width : the maximum line width (number of characters).

break : the string inserted at each wrap point (default is "\n").

cut : boolean flag; when true, the string is cut at the exact width even if a word exceeds the limit.

Return value: the wrapped string with the chosen break characters inserted.

Example 1:

<?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 (cut enabled):

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

Output:

A very<br/>long<br/>wooooooo<br/>ooooord
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.

BackendPHPString Manipulationphp-functionswordwrap
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.