为什么以下代码不起作用??
$test = "hello \n world \n !";
foreach(explode("\n",$test) as $line){
echo $line;
}
打印
hello world !
而不是
hello
world
!
由于
答案 0 :(得分:3)
您还必须回复<br />
HTML
<br />
元素在文本中生成换行符(回车符)。 它对于写一首诗或一个地址很有用 线是重要的。
$test = "hello \n world \n !";
foreach(explode("\n",$test) as $line){
echo $line;
echo "<br />";
}
doc:<br />
另一种选择是使用nl2br
在字符串
$test = "hello \n world \n !";
echo nl2br($test);
Doc:nl2br()
答案 1 :(得分:2)
在HTML中,您需要通过HTML标记为新行添加换行符。如果text / string中有换行符,则不会显示为必需输出。
<br>
用于添加单一换行符。
替换
echo $line;
向
echo $line."<br>";
如果您只需要在源代码中添加新行,请将echo $line;
替换为echo $line."\n";
\n
用于新行的双引号。
无论如何,通过PHP实现此目的的另一种方法是使用PHP的内置方法nl2br()
答案 2 :(得分:1)
$test = "hello \n world \n !";
foreach(explode("\n",$test) as $line){
echo $line;
}
结果是:
hello world !
基本上你已经拆分换行符,并且在打印每个拆分部分时不包括换行符。
答案 3 :(得分:0)
使用nl2br($ line)并用空格替换分隔符。这样你的新行将在html中显示:
$test = "hello \n world \n !";
foreach(explode(" ",$test) as $line){
echo nl2br($line);
}
将输出:
hello
world
!
和输出html:
hello<br />
world<br />
!