$var = "Hi there"."<br/>"."Welcome to my website"."<br/>;" echo $var;
Is there an elegant way to handle line-breaks in PHP? I'm not sure about other languages, but C++ has eol
so something thats more readable and elegant to use?
Thanks
Answer: Use the Newline Characters ' \n ' or ' \r\n ' You can use the PHP newline characters \n or \r\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string.
Definition and Usage. The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.
A line break is a command or sequence of control characters that returns the cursor to the next line and does not create a new paragraph. Essentially, line breaks denote the end of one line and the start of a new one.
For linebreaks, PHP as "\n"
(see double quote strings) and PHP_EOL
.
Here, you are using <br />
, which is not a PHP line-break : it's an HTML linebreak.
Here, you can simplify what you posted (with HTML linebreaks) : no need for the strings concatenations : you can put everything in just one string, like this :
$var = "Hi there<br/>Welcome to my website<br/>";
Or, using PHP linebreaks :
$var = "Hi there\nWelcome to my website\n";
Note : you might also want to take a look at the nl2br()
function, which inserts <br>
before \n
.
I have defined this:
if (PHP_SAPI === 'cli') { define( "LNBR", PHP_EOL); } else { define( "LNBR", "<BR/>"); }
After this use LNBR
wherever I want to use \n
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With