Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant solution for line-breaks (PHP)

$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

like image 969
eozzy Avatar asked Apr 28 '10 04:04

eozzy


People also ask

How can I break line in PHP?

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.

Which tag is used on line break in PHP?

Definition and Usage. The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.

What is Oneline break?

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.


2 Answers

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.

like image 175
Pascal MARTIN Avatar answered Sep 21 '22 13:09

Pascal MARTIN


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.

like image 35
TheVyom Avatar answered Sep 21 '22 13:09

TheVyom