Wrapping Text with PHP wordwrap() Function

Occasionally your PHP script will need to break up a long line of text into several shorter lines while preserving whole words. This can happen if you’re formatting some text for printing or emailing, or you want to display preformatted text in a Web page using the pre element.

PHP gives us a function, wordwrap(), to do this job for you.

The wordwrap() function wraps a string into new lines when it reaches a specific length.

Note: This function may leave white spaces at the beginning of a line.

Syntax :
wordwrap(string,width,break,cut)

Parameters : The function accepts 4 parameters as shown in the above syntax and are described below:

str: This parameter specifies the input string which is needed to break up into lines.

width: This parameter specifies the number of characters at which the string will be wrapped. That is number of characters after whih the string will break.

break: This is an optional parameter and if specified appends the value at the point of breaking the string.

cut: It is a boolean parameter, if this parameter is set to TRUE, then the string is always wrapped at or before the specified width. That is it will also break a word from between if it comes in middle of the constraint specified by the parameter $width. When this parameter is set to FALSE the function does not split the word even if the width is smaller than the word width.

By default, wordwrap() uses a column width of 75 characters. This means that no line will be more than 75 characters long.

Example :

$str = “Webtechsource is IT based company”;
wordwrap($str,17,”\n”,TRUE);

Output :Webtechsource is
IT based company

 

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – we are here to solve your problems.

I, Dayanand Saini,the founder and chief editor of www.webtechsource.com,have been working as a software engineer from last 4+ years. It's my hobby to learn new things and implement on live environment.

Leave a Reply

Your email address will not be published. Required fields are marked *

58 + = 67

%d bloggers like this: