homepage Welcome to WebmasterWorld Guest from 184.72.72.182
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Preg Replace newlines
alphacooler




msg:3023400
 12:38 am on Jul 27, 2006 (gmt 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.

 

eelixduppy




msg:3023410
 12:49 am on Jul 27, 2006 (gmt 0)

Have you tried rtrim [php.net]?

pinterface




msg:3023779
 7:43 am on Jul 27, 2006 (gmt 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. :)

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved