Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Preg Replace newlines

12:38 am on Jul 27, 2006 (gmt 0)

Full Member

10+ Year Member

joined:Feb 4, 2005
votes: 0

I have a form box where users enter in directions (one per line). I then turn each line into a list item <li>. The problem is that when people enter a blank line at the end it creates a new list item.

So I tried the following preg_replace to strip out extra lines at the end of the string. It doesn't work.

$directions = preg_replace('/\r+$/','',$_POST['directions']);

I also tried \n instead of \r.

12:49 am on July 27, 2006 (gmt 0)

Senior Member

WebmasterWorld Senior Member eelixduppy is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 12, 2005
votes: 0

Have you tried rtrim [php.net]?
7:43 am on July 27, 2006 (gmt 0)

Junior Member

10+ Year Member

joined:Jan 28, 2006
votes: 0

\r is not necessarily a newline. The only system I'm aware of where it *is* a newline is older MacOSes. On unix systems a newline is \n, and on windows it is \r\n. To account for this variation, a better regexp would be /[\r\n]+$/; but you might want something more like
preg_split('/[ \t]*[\r\n]+[ \t]*/', trim($foo), -1, PREG_SPLIT_NO_EMPTY)
, which will avoid creating extra <li>s when users put extra lines between items, as well as ignore any leading or trailing spaces on each line. (That trim() is for leading whitespace on the first line and trailing whitespace on the last.)

Of course, if all you want to do is cut out those trailing lines, eelixduppy's suggestion of rtrim() will probably work just dandy. :)


Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members