Elegant solution for line-breaks (PHP)

后端 未结 8 2008
太阳男子
太阳男子 2020-12-08 14:28
$var = \"Hi there\".\"
\".\"Welcome to my website\".\"
;\" echo $var;

Is there an elegant way to handle line-breaks in PHP? I\'

相关标签:
8条回答
  • 2020-12-08 15:24

    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".

    0 讨论(0)
  • 2020-12-08 15:31

    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.

    0 讨论(0)
提交回复
热议问题