Note: \n and \r are special characters that you can't see. They are encoded into the text as line breaks and depending on the system you will have one the other or both (linux, windows, mac). There's really no simple way around this. Using nl2br() seems the easy solution since as far as I've tested it works under all these conditions.
If you want to do it manually, then you must replace three times:
PHP Code:
$var = str_replace("\r\n",'<br>',$var); //for systems that send both as a group
$var = str_replace("\n",'<br>',$var); //for systems that only do \n
$var = str_replace("\r",'<br>',$var); //for system that only do \r
Technically \n is a new line and \r is a carriage return-- the difference? None, really, just that they are both used to encode a "line break". I think it is related to how the page lines up-- if you do a line break it does to a new line but a carriage return goes directly below rather than the other end? Basically once things became digital that was ignored.* Or something. Since I don't really understand the details, I just ignore it all and use nl2br(), though I see no reason that the code I posted above wouldn't work, but also no reason that it's better than nl2br() except that nl2br generates, as far as I've tested it, only <br /> for xhtml if that bothers you. You could also do nl2br() then search and replace <br /> to <br> as needed.
(*I may be entirely wrong in my explanation here, but the background is something like that-- two different types of new lines that eventually served the same purpose. I've never seen the difference explained anywhere except that it's just a remnant of a different system in the past. And perhaps also yet another mac vs. pc operating system thing.)
The only really important part of all this is that you cannot be sure the script is working just testing on your system. Someone else, for example on linux, may have entirely different results. Replacing \r\n will be just fine for windows (I think that's the one for windows...) but it will fail on other systems. Also, depending on how the text is stored it may be automatically converted from one to the other, so it's hard to guess.
As for your code above I don't see anything wrong and the str_replace should be fine. Are you sure there's data output from the database? Try echoing that before the str_replace and that may show the problem is unrelated to the replacing.
Bookmarks