hadoob024 Posted June 7, 2010 Share Posted June 7, 2010 I don't know why I'm blanking on this one. Basically, I have a string containing serial numbers. This string can have multiple newlines and carriage returns actually separating the serial numbers. I want to clean the string so that multiple newlines and carriage returns are removed. However, I still need to separate the remaining serial numbers with a comma. There isn't a consistent naming convention used, and there can be multiple occurrences of these carriage returns and newlines, so I can't just do something like: str_replace("\r\n", "", $mystring) or str_replace("\r\n", ", ", $mystring) So I need something like this: V423060018 V311911037 -or- V265141004 V265141004 V241889035 to be returned as: V423060018, V311911037 -and- V265141004, V265141004, V241889035 respectively. Any thoughts? Quote Link to comment Share on other sites More sharing options...
F1Fan Posted June 7, 2010 Share Posted June 7, 2010 $array = array(); foreach (explode("\r\n", $mystring) as $string){ if (!empty($string)){ $array[] = trim($string); } } echo implode(', ', $array); Quote Link to comment Share on other sites More sharing options...
hadoob024 Posted June 7, 2010 Author Share Posted June 7, 2010 Nice! So that will handle cases with multiple newlines/return carriages, right? Looks good. Just trying to think of a scenario where this won't, but can't seem to think of one. Btw, love the avatar. Headed to Montreal this weekend for the race. Quote Link to comment Share on other sites More sharing options...
Psycho Posted June 7, 2010 Share Posted June 7, 2010 Or even easier: $output = preg_replace("/(\r\n| )+/", ", ", trim($input)); This will replace one (or more in succession) occurances of a line break with a single comma space. Also trims out unneeded extra spaces: $input = "V265141004 V265141004 V241889035 "; $output = preg_replace("/(\r\n| )+/", ", ", trim($input)); echo $output; Output: V265141004, V265141004, V241889035 Quote Link to comment Share on other sites More sharing options...
F1Fan Posted June 7, 2010 Share Posted June 7, 2010 Lucky! That pic is one I took at the 2002 USGP. I also went to the most recent USGP at Indy with a few buddies. Lot's of fun! Quote Link to comment Share on other sites More sharing options...
hadoob024 Posted June 7, 2010 Author Share Posted June 7, 2010 Or even easier: $output = preg_replace("/(\r\n| )+/", ", ", trim($input)); Cool. Thanks for the tip! Lucky! That pic is one I took at the 2002 USGP. I also went to the most recent USGP at Indy with a few buddies. Lot's of fun! Yup. Can't wait. Also can't wait for the race in Austin in 2012! Right now I'm on cruise control until the weekend. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.