PHP: trying to create a new line with “\n”

2019-01-11 06:27发布

i'm writing this:

echo "foo";
echo "\n";
echo "bar";

and "bar" is not written in the line below.

What am i doing wrong?

Javi

标签: php newline
15条回答
叼着烟拽天下
2楼-- · 2019-01-11 06:50

We can apply \n in php by using two type

  1. Using CSS

    body {
        white-space: pre-wrap;
    }
    

    Which tells the browser to preserve whitespace so that

    <body>
        <?php
            echo "Fo\n Pro";
        ?>
    </body>
    

    Result:

    Fo
    Pro

  2. Using nl2br

    nl2br: Inserts HTML line breaks before all newlines in a string

    <?php
        echo nl2br("Fo.\nPro.");
    ?>
    

    Result

    Fo.
    Pro.

查看更多
女痞
3楼-- · 2019-01-11 06:51

If you want a new line character to be inserted into a plain text stream then you could use the OS independent global PHP_EOL

echo "foo";
echo PHP_EOL ;
echo "bar";

In HTML terms you would see a newline between foo and bar if you looked at the source code of the page.

ergo, it is useful if you are outputting say, a loop of values for a select box and you value having html source code which is "prettier" or easier to read for yourself later. e.g.

foreach( $dogs as $dog )
echo "<option>$dog</option>" . PHP_EOL ;
查看更多
成全新的幸福
4楼-- · 2019-01-11 06:53

if your text has newlines, use nl2br php function:

<?php
$string = "foo"."\n"."bar";
echo nl2br($string);
?>

This should look good in browser

查看更多
该账号已被封号
5楼-- · 2019-01-11 06:55

Since it wasn't mentioned, you can also use the CSS white-space property

body{
    white-space:pre-wrap;
}

Which tells the browser to preserve whitespace so that

<body>
    <?php
        echo "hello\nthere";
    ?>
</body>

Would display

hello
there
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-11 06:55

We can use \n as a new line in php.

Code Snippet :

 <?php
  echo"Fo\n";
  echo"Pro";
?>

Output:

Fo
Pro

查看更多
虎瘦雄心在
7楼-- · 2019-01-11 06:59
$a = 'John' ; <br/>
$b = 'Doe' ; <br/>
$c = $a.$b"&lt;br/>";
查看更多
登录 后发表回答