PHP String wordwrap() Function
The wordwrap() string function is an in-built function of PHP. It is used to wrap a string to the given number of characters using a string break character. PHP 4.0.2 and above versions support this function. In simple words, it wraps a string into new lines when it reaches to its given length.
Note: This function may leave whitespaces at the beginning of the line.
The syntax of the wordwrap() function is given below, that accepts four arguments.
The wordwrap() function accepts four arguments, in which only $string parameter is mandatory to pass, and the other three arguments are optional. These arguments are discussed below in detail:
$string (required): It is a mandatory parameter of this function. It specifies the input string that needs to break up into lines.
$width (optional): It is an optional parameter of this function. It specifies the maximum line width. By default, it takes 75.
$break (optional): It is an optional parameter of this function. It provides a character to use as a break. By default is "\n".
$cut (optional): It is also an optional parameter of this function, which contains the Boolean value. By default, the wordwrap() takes the Boolean value as "FALSE" for this parameter:
The wordwrap() function returns the string wrapped by the specified length, i.e., the string is broken into lines on success, and return FALSE on failure.
The $cut parameter was added in PHP 4.0.3.
There are some examples, by which we can learn the working of wordwrap() function. Let's see the given examples below:
In the above example, a string is broken after every ten characters by the newline character. Here, we did not pass the $cut parameter.
An example of the wordwrap() function to break the string
Note: This function does not break a word from between when the fourth parameter is not passed as TRUE, even if the given width is less than the word width.
In this example, we did not break "Congratulations" word from the given width, i.e., 8, because this function does not break character in between.
Congratulations! to all
Example 3: When $cut is passed as "TRUE"
In this example, we break "Congratulations" word from the given width, i.e., 8, and passed $cut parameter whose value is TRUE. So this function breaks the string after every eight characters.
Congratu lations! to all
Example 4: When $cut is passed as "FALSE"
Be a part of javatpoint