如何在 PHP 中编写多行字符串

Minahil Noor 2023年1月30日 PHP PHP String
  1. 在 PHP 中使用转义序列编写多行字符串的方法
  2. 在 PHP 中使用连接赋值运算符写多行字符串的方法
如何在 PHP 中编写多行字符串

本文将介绍在 PHP 中编写多行字符串的不同方法。

在 PHP 中使用转义序列编写多行字符串的方法

在 PHP 中,我们有多个转义序列。我们在这里只提两个。最简单的方法是使用\n 转义序列。我们用双引号来使用这个转义序列。使用这个转义序列的正确语法如下。

echo("\n");

下面的程序显示了我们在 PHP 中使用\n 转义序列编写多行字符串的方法。

<?php
echo("This is the first line \nThis is the second line");
?>

输出:

This is the first line 
This is the second line

我们可以使用两次 \n 在两行文本之间创建一个空行。

<?php
echo("This is the first line \n\nThis is the third line");
?>

输出:

This is the first line 

This is the third line

我们也可以使用\r\n 转义序列来写多行字符串。它也会创建新行,因为它是回车。回车会重置指针并从左边开始。正确使用它的语法如下。

echo("\r\n");

应用这种方法来写多行字符串的程序如下:

<?php
echo("This is the first line \r\nThis is the third line");
?>

输出:

This is the first line 
This is the third line

在 PHP 中使用连接赋值运算符写多行字符串的方法

在 PHP 中,我们还可以使用连接赋值运算符来编写多行字符串。连接赋值运算符是 .=。连接赋值运算符将字符串追加到右边。我们还将使用 PHP_EOL 来创建一个新行。正确使用该运算符的语法如下。

$string1 .= $string2;

这些变量的详细信息如下。

变量 说明
$string1 它是我们要在右边附加一个新字符串的字符串
$string2 它是我们要与第一个字符串进行连接的字符串

下面的程序展示了我们如何在 PHP 中使用连接赋值运算符和 PHP_EOL 来编写多行字符串。

<?php
$mystring1 = "This is the first line." . PHP_EOL;
$mystring2 = "This is the second line";
$mystring1 .= $mystring2;
echo($mystring1);
?>

输出:

This is the first line.
This is the second line

同样,我们也可以用这个操作符来写 N 个多行字符串。

<?php
$mystring1 = "This is the first line." . PHP_EOL;
$mystring2 = "This is the second line" . PHP_EOL;
$mystring3 = "This is the third line" . PHP_EOL;
$mystring4 = "This is the fourth line" . PHP_EOL;
$mystring5 = "This is the fifth line";
$mystring1 .= $mystring2 .= $mystring3 .= $mystring4 .= $mystring5;
echo($mystring1);
?>

输出:

This is the first line.
This is the second line
This is the third line
This is the fourth line
This is the fifth line
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

相关文章 - PHP String