如何在PHP中创建换行符()

为了创建换行符, PHP提供了nl2br()函数。它是PHP的内置函数, 用于在字符串中的所有换行符之前插入HTML换行符。虽然, 我们也可以在源代码中使用PHP换行符\ n或\ r \ n来创建换行符, 但是这些换行符在浏览器中不可见。因此, nl2br()在这里很有用。
nl2br()函数包含这些换行符\ n或\ r \ n, 它们共同创建换行符。除了nl2br()函数外, 还使用html换行符< /br> 来分隔字符串。 < /br> 标签应该用双引号引起来, 例如” < /br> ” 。
例如
为了用PHP创建换行符, 让我们看一些例子。
例子1
让我们举一个例子, 借助nl2br()函数创建换行符。

< ?php echo nl2br("New line will start from here\n in this string\r\n on the browser window"); ?>

输出
在此示例中, 我们可以看到nl2br()函数在换行符字符串中包含” \ n” 和” \ r \ n” 字符。我们可以在下面的输出中看到以下程序的结果。
New line will start from herein this stringon the browser window

例子2
< ?php echo "One line after\n another line"; echo " One line after\r\n another line"; ?>

输出
在上面的示例中, 我们可以看到, 在” \ n” 或” \ r \ n” 字符之后, 字符串不是从新行开始的。仅使用” \ n” 和” \ r \ n” 不足以在字符串中创建换行符, 因为整个字符串显示在一行中。
One line after another line One line after another line

注意:在Linux中, 字符” / n” 用于写换行符, 而在Windows中, 字符” / n” 用于写换行符。为了安全起见, 请使用” \ r \ n” 字符来创建换行符。例子3
< ?php echo "One line after\n another line"; echo "< /br> "; echo "One line after\r\n another line"; ?>

输出
【如何在PHP中创建换行符()】在这里, 我们使用html换行标记” < /br> ” 来换行。
One line after another lineOne line after another line

    推荐阅读