Introduction

The wordwrap() function in PHP is used to wrap a string to a specified number of characters. It inserts line breaks at the appropriate points to ensure that no line of text exceeds the specified width.

Here is the syntax of the wordwrap() function:

wordwrap(string, width, break, cut)

The first argument is the string to be wrapped. The second argument is the width at which to wrap the text. The third argument is the character or string to use as a line break. By default, the line break is a newline character ("\n"). The fourth argument is a boolean value that determines whether to cut words that are too long to fit on a line. By default, words are not cut.

Example

Here is an example of how to use wordwrap():

<?php

$text = "This is a long piece of text that needs to be wrapped.";
$wrapped_text = wordwrap($text, 20, "\n");
echo $wrapped_text;

This will output:

This is a long piece
of text that needs
to be wrapped.

In this example, the wordwrap() function has wrapped the text so that no line of text exceeds 20 characters. The line breaks are inserted using the newline character "\n".

Practice Your Knowledge

What does the PHP wordwrap() function do?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?