在 PHP 回显字符串中使用行尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6519976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:37:47  来源:igfitidea点击:

Using end of line in PHP echo string

php

提问by Ismael

I am trying to write a PHP script that echos a string, but it doesn't recognize the end of line function in there.

我正在尝试编写一个包含echo字符串的 PHP 脚本,但它无法识别其中的行尾函数。

For example,

例如,

echo "thank you \n "
echo "for coming over"

The \nis ignored and it prints the whole line as thank you for coming over.

\n被忽略,它打印整个行thank you for coming over

I got the same result for the following to:

对于以下内容,我得到了相同的结果:

echo "thank you " . PHP_EOL.;
echo "for coming over" . PHP_EOL.;

回答by hakre

There are different ways to solve that:

有不同的方法可以解决这个问题:

Using Pre-formatted text

使用预先格式化的文本

echo '<pre>'; // pre-formatted text, \n should work
echo "thank you \n ";
echo "for coming over";
echo '</pre>';

Changing the content type

更改内容类型

header('Content-Type: text/plain');
echo "thank you \n ";
echo "for coming over";

You browser will now properly read the output as text.

您的浏览器现在可以正确地将输出读取为文本。

Using the HTML break element

使用 HTML 中断元素

echo "thank you <br>\n ";
echo "for coming over";

So output always depends on what you want to output. Is it text? Is it HTML? Is it some text within HTML? Depending on what you need you should take care on the format and formatting.

所以输出总是取决于你想输出什么。是文字吗?是 HTML 吗?它是 HTML 中的一些文本吗?根据您的需要,您应该注意格式和格式。

回答by Tim Cooper

If you are doing this in a browser, replace \nwith <br />. The file line breaks are not rendered in an HTML page, unless specified via CSS or if they're enclosed in certain tags. You could also optionally change the file type to text/plain, but I don't think that would be desired.

如果您在浏览器中执行此操作,请替换\n<br />. 除非通过 CSS 指定或包含在某些标签中,否则文件换行符不会在 HTML 页面中呈现。您还可以选择将文件类型更改为text/plain,但我认为这不是所希望的。

回答by user948319

try this normally you can use

试试这个通常你可以使用

 echo "thank you <br>";
 echo "for coming over<br>";

and at time of file handling

和文件处理时

echo "thank you ".PHP_EOL."";
echo "for coming over".PHP_EOL."";

回答by middus

If you want to print text containing eol's in html, give nl2bra shot

如果你想打印包含EOL在HTML文本,给nl2br出手

$str = "thank you \n ";
$str .= "for coming over";
nl2br($str);

It will add HTML line breaks before all eols.

它将在所有 eol 之前添加 HTML 换行符。

回答by balki

Check the source of the web page from browser, there will be a new line. Since in HTML, whitespaces like newline, tabs or spaces are ignored, you can't see them in the browser. You need to use <br />or &nbsp;etc. to print what you want.

从浏览器检查网页的来源,会有一个新行。由于在 HTML 中,诸如换行符、制表符或空格之类的空格会被忽略,因此您无法在浏览器中看到它们。您需要使用<br />&nbsp;等来打印您想要的内容。