0

I am trying to create line breaks in my php script. I have variables using session, and I cannot figure out how to create line breaks with them. I have tried the following (as well as different combinations) as well as googling to try and find a solution with absolutely no luck at all.

 <?php

session_start();

$_SESSION['firstname'] = $_POST['firstname'];
$_SESSION['lastname'] = $_POST['lastname'];

echo nl2br("First Name : $_SESSION['firstname']\n\r");
echo nl2br("Last Name : $_SESSION['lastname']\n\r");
?>

I am grabbing variables from a form on a previous page. If I just echo the variables like so,

<?php

session_start();

$_SESSION['firstname'] = $_POST['firstname'];
$_SESSION['lastname'] = $_POST['lastname'];

echo $_SESSION['firstname'];
echo $_SESSION['lastname'];
?>

It works just fine. I am having a difficult time trying to find out how to use the syntax of nl2br (which I have also successfully used before) with session variables in php.

Any help is greatly appreciated. Thanks!

-Anthony

UPDATE: Answer below via Marc B. When session variables are in double-quotes, single-quotes must be removed.

<?php

session_start();

$_SESSION['firstname'] = $_POST['firstname'];
$_SESSION['lastname'] = $_POST['lastname'];

echo nl2br("First Name : $_SESSION[firstname]\n\r");
echo nl2br("Last Name : $_SESSION[lastname]\n\r");
?>
aCarella
  • 2,369
  • 11
  • 52
  • 85
  • Look at the section on `unexpected T_ENCAPSED_AND_WHITESPACE` [this reference question](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/13935532#13935532) for suggestions on how to quote it correctly. Your problem isn't specific to `nl2br()`, but just with the general behavior of double-quoted strings with complex variables. – Michael Berkowski Mar 31 '14 at 19:10
  • Also, linebreaks as a combination of carriage-return, newline are `\r\n`, not `\n\r` as you have them. – Michael Berkowski Mar 31 '14 at 19:13

2 Answers2

2

nl2br is a glorified remake of str_replace("\n", "<br />", $text). If your string doesn't have ANY newline characters, there's nothing to replace and you've basically got an expensive print/echo occuring.

You also have PHP syntax errors. You cannot use quoted array keys in a double-quoted string:

echo "$array[key]"; // ok
echo "$array['key']"; // wrong
echo "{$array['key']}"; // ok - extended syntax.
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • nl2br is a **little** bit more fancy than that: it does not replace, but adds
    , and it detects more than \n linebreaks
    – Jasper Mar 31 '14 at 19:53
0
echo nl2br("First Name" . $_SESSION['firstname'] . "\r\n");
echo nl2br("First Name" . $_SESSION['lastname'] . "\r\n");

Or could you try?

echo "First Name".$_SESSION['firstname']."<br />";
echo "Last Name".$_SESSION['lastname']."<br />";
lxndr
  • 702
  • 1
  • 11
  • 25