首页 > 解决方案 > 如何在 php 代码中添加新行/换行符

问题描述

我想知道是否有人可以帮助我。我比 php 更了解 html。

我需要在此处的地址字符串的每个部分之后放置一个换行符。

<?php echo $this->get_detail($order, 'address_1');?>
<?php
$address2 = $this->get_detail($order, 'address_2');
$country = $this->get_detail($order, 'country');
if (!empty($address2)) echo ", ".$this->get_detail($order, 'address_2');
?>
, <?php echo $this->get_detail($order, 'city');?>, <?php echo $this- 
>get_detail($order, 'state');?>, <?php echo $this->get_detail($order, 
'postcode'); ?> <?php
if ($country) echo ", ".$country;   
?>

所以地址1之后的新行,地址2之后的新行等等我该怎么做?我已阅读有关 \n 的信息,但不知道该放在哪里。

另外我想在标题“客户注释:”的上方和下方放置一个行空间,这会产生

$customer_note = is_callable(array($order, 'get_customer_note')) ? $order- 
>get_customer_note() : $order->customer_note;
if ($customer_note) {
echo __('Customer Note:', 'woocommerce').' '.$customer_note."\n";
}

同样,我不确定如何最好地做到这一点。非常欢迎任何帮助。

因此,上述两个代码目前产生的是:

门牌号和街道、城镇、县、邮政编码、国家客户备注:这是客户备注 blah blah blah.....

我希望它看起来像这样:

门牌号和街道
城镇

邮政编码
国家


客户备注:


这是客户备注等等等等......

标签: php

解决方案


\n是换行符。


使用\n

1.直接回显到页面

现在,如果您尝试将字符串回显到页面:

echo  "kings \n garden";

输出将是:

kings garden

您不会garden换行,因为 PHP 是一种服务器端语言,并且您将输出作为 HTML 发送,您需要在 HTML 中创建换行符。HTML 看不懂\n。您需要为此使用该nl2br()功能。

它的作用是:

返回在所有换行符(\r\n、\n\r、\n 和 \r)之前插入<br />或插入的字符串。<br>

echo  nl2br ("kings \n garden");

输出

kings
garden

注意确保您\n在双引号中回显/打印,否则它将按字面意思呈现为 \n。因为 php 解释器用as is的概念解析单引号中的字符串

so "\n" not '\n'

2.写入文本文件

现在,如果您回显到文本文件,您可以使用 just \n,它将回显到新行,例如:

$myfile = fopen("test.txt", "w+")  ;

$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
 

输出将是:

kings
 garden

推荐阅读