做一个勇于分享的php园丁

PHP开发园地

PHP中使文本在特定长度处自动换行

PHP中你可以对一个字符串进行换行处理。例如,你想显示<pre>/</pre>标记中的文本,但希望这些文本能在正常大小的浏览器窗口中自动地换行。这时候我们可以PHP中的wordwrap()函数,如下代码所示:

<?php
$s = "Four score and seven years ago our fathers brought forth↵
on this continent a new nation, conceived in liberty and↵
dedicated to the proposition that all men are created equal.";
print "<pre>\n".wordwrap($s)."\n</pre>";
?>
输出结果:

<pre>
Four score and seven years ago our fathers brought forth on this continent
a new nation, conceived in liberty and dedicated to the proposition that
all men are created equal.
</pre>
在默认情况下,wordwrap()会按照每行75个字符来自动将文本换行。使用可选的第二个参数来指定不同的行长度,如下PHP代码所示:

<?php
print wordwrap($s,50);
?>
这样,其输出结果就变成了:

Four score and seven years ago our fathers brought
forth on this continent a new nation, conceived in
liberty and dedicated to the proposition that all
men are created equal.
除了\n之外的其他字符也可以作为换行符。要想输出两个空行,可以用“\n\n“

<?php
print wordwrap($s,50,"\n\n");
?>
其输出结果:

Four score and seven years ago our fathers brought
forth on this continent a new nation, conceived in
liberty and dedicated to the proposition that all
men are created equal.
wordwrap()还有可选的第四个参数,用于控制对那些比指定的行长度值更长的单词的处理方式。如果这个参数值为1,超出指定长度的这些单词会换行;否则,这些单词就会保留原来的行长度:

<?php
print wordwrap('jabberwocky',5);
print wordwrap('jabberwocky',5,"\n",1);
?>
其输出结果:

jabberwocky
jabbe
rwock
y
好了,PHP中使文本在特定长度处自动换行就介绍到这里了。

转载请注明:http://www.itivy.com/php/archive/2012/2/16/php-wordwrap-usage.html

标签: PHP, wordwrap(), 换行

我也来参与讨论

  1. 回复 2012-2-19 1:36:00 by bigtt

    不错
  2. 回复 2012-2-19 1:38:07 by gsergb

    不错
你还可以输入600/600个字符 发表评论
称呼: (必填) 登录 | 开通博客
邮箱: (选填) 你的邮箱地址不会被公开
网站: (选填)
验证码: (必填)
看不清换一张 看不清楚换一张