1

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?
1
  • When I did a test run of echo '<b>Detail: </b>' .nl2br($detail). '<br />' by itself, it seemed to work and would show the spaces and not \r\n. Only here it doesn't seem to work
    – ggfan
    Mar 31, 2010 at 18:27

3 Answers 3

2
$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.

3
  • thank you very much! Got it to work. Hate those \r\n things :/
    – ggfan
    Mar 31, 2010 at 18:36
  • Haha no problem, just make sure no one types in \r since you are filtering it out. Cheers mate.
    – JonnyLitt
    Mar 31, 2010 at 18:37
  • @ggfan you kidding. are you really do that stupid str_replace('\r', '', $input)? Mar 31, 2010 at 18:44
0

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().

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.