Print newline in PHP in single quotes

前端 未结 12 1201
野性不改
野性不改 2020-11-28 21:33

I try to use single quotes as much as possible and I\'ve noticed that I can\'t use \\n in single quotes. I know I can just enter a newline literally by pressing return, but

相关标签:
12条回答
  • 2020-11-28 21:53

    No, because single-quotes even inhibit hex code replacement.

    echo 'Hello, world!' . "\xA";
    
    0 讨论(0)
  • 2020-11-28 21:56

    You may want to consider using <<<

    e.g.

    <<<VARIABLE
    this is some
    random text
    that I'm typing 
    here and I will end it with the 
    same word I started it with
    VARIABLE
    

    More info at: http://php.net/manual/en/language.types.string.php

    Btw - Some Coding environments don't know how to handle the above syntax.

    0 讨论(0)
  • 2020-11-28 21:57

    There IS a difference on using single VS double quotes in PHP

    e.g: 1. echo '$var\n'; 2. echo "$var\n";

    • in 1, PHP will print literally: $var\n
    • in 2, PHP will have to search the location in memory for $var, and return the value in that location, also, it will have to parse the \n as a new line character and print that result

    We're in the range of millionths of a second, but there IS a difference in performance. I would recommend you to use single quotes whenever possible, even knowing you won't be able to perceive this performance increase. But I'm a paranoid developer when it comes to performance.

    0 讨论(0)
  • 2020-11-28 21:59

    If you are echoing to a browser, you can use <br/> with your statement:

    echo 'Will print a newline<br/>';
    echo 'But this wont!';
    
    0 讨论(0)
  • 2020-11-28 22:01

    FYI it is possible to get newlines into strings without double quotes:

    printf('Please%1$sgive%1$sme%1$snewlines%1$s', PHP_EOL);
    

    Which may be useful If your irrational fear of double quotes knows no bounds. Though I fear this cure may be worse than the disease.

    0 讨论(0)
  • 2020-11-28 22:03

    You can use this:

    echo 'Hello World' . "\n";
    
    0 讨论(0)
提交回复
热议问题