PHP String - wordwrap() Function
The PHP wordwrap() function wraps a string to a given number of characters using a string break character.
Syntax
wordwrap(string, width, break, cut_long_words)
Parameters
string |
Required. Specify the input string. |
width |
Optional. Specify the number of characters at which the string will be wrapped. Default is 75. |
break |
Optional. Specify the characters to use as break. Default is "\n". |
cut_long_words |
Optional. If set to true, the string is always wrapped at or before the specified width. When set to false the function does not split the word even if the width is smaller than the word width. Default is false. |
Return Value
Returns the given string wrapped at the specified length.
Example:
The example below shows the usage of wordwrap() function.
<?php $str = "The quick brown fox jumped over the lazy dog."; $wrapped_str = wordwrap($str, 20); //displaying the wrapped string echo $wrapped_str; ?>
The output of the above code will be:
The quick brown fox jumped over the lazy dog.
Example:
Consider one more example where the fourth parameter is used to handle long words.
<?php $str = "A very long woooooooooooord."; //do not split the long words $wrapped_str1 = wordwrap($str, 10, "\n"); //splits the long words $wrapped_str2 = wordwrap($str, 10, "\n", true); //displaying the wrapped string echo $wrapped_str1; echo "\n\n"; echo $wrapped_str2; ?>
The output of the above code will be:
A very long woooooooooooord. A very long wooooooooo ooord.
❮ PHP String Reference