如何在 PHP 中編寫多行字串
Minahil Noor
2023年1月30日
PHP
PHP String

本文將介紹在 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