[php] 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

This question is related to php line-breaks

The answer is


Well, as with any language there are several ways to do it.

As previous answerers have mentioned, "<br/>" is not a linebreak in the traditional sense, it's an HTML line break. I don't know of a built in PHP constant for this, but you can always define your own:

// Something like this, but call it whatever you like
const HTML_LINEBREAK = "<br/>";

If you're outputting a bunch of lines (from an array of strings for example), you can use it this way:

// Output an array of strings
$myStrings = Array('Line1','Line2','Line3');
echo implode(HTML_LINEBREAK,$myStrings);

However, generally speaking I would say avoid hard coding HTML inside your PHP echo/print statements. If you can keep the HTML outside of the code, it makes things much more flexible and maintainable in the long run.


in php line breaks we can use PHP_EOL (END of LINE) .it working as "\n" but it cannot be shown on the ht ml page .because we have to give HTML break to break the Line..

so you can use it using define

define ("EOL","<br>");

then you can call it


\n didn't work for me. the \n appear in the bodytext of the email I was sending.. this is how I resolved it.

str_pad($input, 990); //so that the spaces will pad out to the 990 cut off.


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.


Not very "elegant" and kinda a waste, but if you really care what the code looks like you could make your own fancy flag and then do a str_replace.

Example:<br />
$myoutput =  "After this sentence there is a line break.<b>.|..</b> Here is a new line.";<br />
$myoutput =  str_replace(".|..","&lt;br />",$myoutput);<br />

or

how about:<br />
$myoutput =  "After this sentence there is a line break.<b>E(*)3</b> Here is a new line.";<br />
$myoutput =  str_replace("E(*)3","&lt;br />",$myoutput);<br />

I call the first method "middle finger style" and the second "goatse style".


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.


Because you are outputting to the browser, you have to use <br/>. Otherwise there is \n and \r or both combined.