Jump to content

Need a more powerful str_replace()


hadoob024

Recommended Posts

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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

 

 

Link to comment
Share on other sites

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. 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.