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)

10+ Year Member

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 Jul 27, 2006 (gmt 0)

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

Have you tried rtrim [php.net]?


7:43 am on Jul 27, 2006 (gmt 0)

5+ Year Member

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


Featured Threads

Hot Threads This Week

Hot Threads This Month