We hope you enjoy your visit.

You're currently viewing our forum as a guest. This means you are limited to certain areas of the board and there are some features you can't use. If you join our community, you'll be able to access member-only sections, and use many member-only features such as customizing your profile, sending personal messages, and voting in polls. Registration is simple, fast, and completely free.


Join our community!


If you're already a member please log in to your account to access all of our features:

Username:   Password:
Add Reply
Adding Line Breaks; Easy way with PHP?
Topic Started: Jun 26 2005, 08:41 PM (450 Views)
Dennis
Member
[ *  *  *  *  *  *  * ]
What is the easiest way to automagically(tm) add <br /> tags to each line break?

i.e. A user types a comment, and clicks enter, for a line break. Then when the comment is added, it automatically replaces the break with a <br /> tag.
Offline Profile Quote Post Goto Top
 
FearKiller
Member Avatar
www.drewscripts.com
[ *  *  *  *  * ]
Code:
 
$message = nl2br($message);
Offline Profile Quote Post Goto Top
 
James
Live to Dream
[ *  *  *  *  *  *  * ]
Wow. And i've been doing str_replace's on \n and \r\n for ages :)
Offline Profile Quote Post Goto Top
 
FearKiller
Member Avatar
www.drewscripts.com
[ *  *  *  *  * ]
Although that function exists I don't use it either. This is what I use to take care of line breaks.

Code:
 
$nl = array();
$nl[] = "/(\r\n|\n|\r)/";
$nl[] = "/\n\n+/";
$nl[] = "/\n/";

$br = array();
$br[] = "\n";
$br[] = "\n\n";
$br[] = '<br />';

$message = preg_replace($nl, $br, $message);


This better helps to prevent abuse as it stops users from putting multiple line breaks and creating





















large






















blank




























messages. :P
Offline Profile Quote Post Goto Top
 
Jeremy
Member Avatar
Member
[ *  *  *  *  *  * ]
James
June 27, 2005 02:09 AM
Wow. And i've been doing str_replace's on \n and \r\n for ages :)

Depending on what you code for, that's the better method...

Code:
 
preg_replace("/(\n|\r\n)/", "<br />", $string);


That's what I use. If you need something to prevent multiple line breaks, there's an easier regular expression than what FearKiller mentioned, but I won't get into that, here. :)
Offline Profile Quote Post Goto Top
 
Dennis
Member
[ *  *  *  *  *  *  * ]
@FK: I'll definitely use that, but in this case, it's only for a site news script, so I'm not really worried about people abusing it. So the nl2br function works for now.
Offline Profile Quote Post Goto Top
 
1 user reading this topic (1 Guest and 0 Anonymous)
« Previous Topic · Technology Chat · Next Topic »
Add Reply