Home  >  Article  >  Backend Development  >  PHP function wordwrap() that wraps strings according to the specified length

PHP function wordwrap() that wraps strings according to the specified length

黄舟
黄舟Original
2017-11-07 09:24:481656browse

Example

Wrap string according to the specified length:

<?php
$str = "An example of a long word is: Supercalifragulistic";
echo wordwrap($str,15,"<br>n");
?>

Definition and usage

wordwrap() function according to the specified length Wrap the string.

Note: This function may leave spaces at the beginning of lines.

Syntax

wordwrap(string,width,break,cut)
Parameters Description
string Required. Specifies the string to be wrapped.
width Optional. Specifies the maximum line width. The default is 75.
break Optional. Specifies the character used as a delimiter (string breaking character). The default is "\n".
cut Optional. Specifies whether words larger than the specified width should be wrapped:
  • FALSE - Default. No line wrapping

  • TRUE - Line wrapping

##Technical details

Return value: If successful, the wrapped string is returned. On failure, returns FALSE. PHP Version: 4.0.2+In PHP 4.0.3, the cut parameter is added.

更多实例

实例 1

使用所有的参数:

<?php
$str = "An example of a long word is: Supercalifragulistic";
echo wordwrap($str,15,"<br>n",TRUE);
?>

实例 2

对字符串进行折行:

<?php
$str = "An example of a long word is: Supercalifragulistic";
echo wordwrap($str,15);
?>

上面代码的 HTML 输出如下(查看源代码):

<!DOCTYPE html>
<html>
<body>
An example of a
long word is:
Supercalifragulistic
</body>
</html>

上面代码的浏览器输出如下:

An example of a long word is: Supercalifragulistic

wordwrap()函数可以按照指定的固定行长度格式化文本段落,让段落看起来更加整齐

<?php
$string = "TRADING ON MARGIN POSES ADDITIONAL
RISKS AND IS NOT SUITABLE FOR ALL
    INVESTORS.
A COMPLETE LIST OF THE RISKS ASSOCIATED WITH MARGIN TRADING IS
AVAILABLE IN THE MARGIN RISK DISCLOSURE DOCUMENT.";
$string = str_replace("\n", " ", $string);
$string = str_replace("\r", " ", $string);
print(wordwrap($string, 40)."\n");
?>

上面的代码返回如下结果

TRADING ON MARGIN POSES ADDITIONAL
RISKS AND IS NOT SUITABLE FOR ALL
INVESTORS. A COMPLETE LIST OF THE
RISKS ASSOCIATED WITH MARGIN TRADING IS
AVAILABLE IN THE MARGIN RISK DISCLOSURE
DOCUMENT.


Change Log:

The above is the detailed content of PHP function wordwrap() that wraps strings according to the specified length. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn