我已经开始学习PHP了。在我的第一个代码中,换行不正确。我已经阅读了PHP文档,但我仍然没有遇到问题。
<?php
# Echoing
echo "Hello World to PHP \n";
echo "Concatenation in PHP is done using ." . "Vivek kumar" . "Learning php";
# Variable Basics
$name = "Vivek Kumar";
$age = 26;
echo "My name is $name and age is $age .";
echo 'My name is '. $name . ' and age is ' . $age . '.';
?>
输出:
Hello World to PHP PHP中的连接是使用.Vivek完成的 kumarLearning php我的名字是Vivek Kumar,年龄是26岁。我的名字是 Vivek Kumar和年龄是26岁。
答案 0 :(得分:2)
我假设您将输出回显到您使用Web浏览器查看的html页面?在这种情况下,换行符 do 会被复制到输出中,但是它们不会这样显示。这只是因为在html标记中,换行符与纯文本文件不同。
检查<br>
或<br />
换行符对此类标记的使用情况。 php也为此提供了方便的nl2br()
功能。
此类输出的示例(请参阅here):
Hello World to PHP Concatenation in PHP is done using .
<br />
Vivek kumarLearning phpMy name is Vivek Kumar and age is 26 .
<br />
My name is Vivek Kumar and age is 26.
但总的来说,你应该考虑一下将这些字符串放入html标记时是否真的只想连接这些字符串。通常,您希望将它们包装在(不可见)容器(如跨度,div或段落)中,以便您可以使用样式(样式表/ css)控制最终布局。
一个任意的例子(见here)
HTML:
<div id="intro">Hello World to PHP Concatenation in PHP is done using .</div>
<h2>Vivek kumarLearning php</h2>
<div class="plain">My name is Vivek Kumar and age is 26 .</div>
<div class="plain">My name is Vivek Kumar and age is 26.</div>
CSS:
body {
font-size: 130%;
}
#intro {
font-weight: bold;
margin-bottom: 10px;
}
.plain {
font-size: 100%;
}
答案 1 :(得分:1)
您可以使用nl2br
将新行(\n
)转换为换行符(<br>
)。
来自http://php.net/manual/en/function.nl2br.php:
string nl2br ( string $string [, bool $is_xhtml = true ] )
返回在所有换行符(<br />
)之前插入<br>
或\r\n, \n\r, \n and \r
的字符串。
或者您可以像其他人建议的那样使用换行符。从表单文本区域显示文本时,nl2br
非常方便。
答案 2 :(得分:0)
如果您在浏览器中使用此功能,则应使用<br>
标记,或者使用<pre>
我发布了<pre>
和<br>
**with `<pre>`**
<?php
# Echoing
echo '<pre>';
echo "Hello World to PHP "."\n";
echo "Concatenation in PHP is done using ." . "Vivek kumar" . "Learning php";
echo '<pre>';
与
echo "Hello World to PHP "."<br/>";
echo "Concatenation in PHP is done using ." . "Vivek kumar" . "Learning php";