php - 如何在 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.....
我希望它看起来像这样:
门牌号和街道
城镇
县
邮政编码
国家
客户备注:
这是客户备注等等等等......
解决方案
\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
推荐阅读
- junit - Jigsaw 从测试中读取资源
- visual-studio-code - 编辑 Prettier (VS-Code) CSS 格式设置
- python - 是否可以在 python 中为 dict 行设置别名?
- javascript - React Native - 博览会小吃和本地环境产生不同的结果
- python - Numba 不会显着加速递归二分搜索
- mongodb - 查找嵌入文档是否存在于数组中并获取父文档的a属性值
- python-3.x - 如何将'Sat Feb 02 12:50:00 IST 2019'转换为python中的常规日期时间?
- javascript - 无法创建 package.json
- flutter - 如何在颤动中不断改变背景
- css-animations - 如何使动画绘制边框?(需要香草 JS 解决方案)