ggfan
ggfan

Reputation: 2492

Why is my nl2br() function displaying \r instead of a break(<br />)? PHP

When I use the function nl2br($text) it doesn't display the breaks I want it to but instead shows the \r of where the breaks are to be. I am display a confirmation page for a user that shows the detail they entered in the form.

(the confirmation code in php)
// Confirm success with the user
    echo '<p>You have successfully posted a ad.'; 
    echo 'Here is your posting: <br /><br />';
    echo 'Title: ' .$title. '<br />' ;
    echo 'Price $: ' .$price.'<br />' ;
    echo 'Location: ' .$city. ' ' .$state. '<br />' ;
    echo '<b>Detail: </b>' .nl2br($detail). '<br />';

(The form users fill out)
<div class="fieldwrapper">
<label for="detail" class="styled">Detail:</label>
<div class="thefield">
    <textarea id="detail" name="detail"><?php if (!empty($detail)) echo $detail; ?></textarea>

(The output)
This is a test\r\n\r\ntesting is good\r\n\r\nWhy doesn\'t it work?

Upvotes: 1

Views: 911

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 158003

\r were already in your text. not a carriage return sumbols but literally 2-symbol sequence - a backslash fllowed by r letter. You have to find a place in your code that converts newlines to \r sequences. addslashes after mysql_real_escape_string() may do the thing

Update:
After your comment I got it. You 're using single quotes to delimit your string.
REad PHP syntax and don't worry. The real data would be fine.

Upvotes: 0

Peter Bailey
Peter Bailey

Reputation: 105914

Because \r is not a newline character in the *nix sense (aka "line feed" character) - it's a "carriage return" character.

There's historical reasons why both exist, but these days it's just really an annoyance that us programmers have to deal with.

As JonnyLitt answered - you'll have to remove the \r characters yourself prior to using nl2br().

Upvotes: 0

JonnyLitt
JonnyLitt

Reputation: 773

$input = 'this \r\nis what\r\ni want\r\n\r\n\r\nd'; 
echo nl2br(str_replace('\r', '', $input);

Remove \r first and that should help.

Upvotes: 2

Related Questions