skyer2000 Posted September 9, 2008 Share Posted September 9, 2008 Quick question, Lets say I have a string that says "John Doe, Nancy Palin, George Johnson". I want to switch it to "Doe, John, Nancy Palin, George Johnson". How would I do that? Is it some sort of string replace? Quote Link to comment Share on other sites More sharing options...
DarkWater Posted September 9, 2008 Share Posted September 9, 2008 You only want the first name switched? And lol @ Sarah Palin and her horrid sense of humor. I bet you all the hockey moms were pissed. Edit: I was just heard someone say Nancy Pelosi so I accidentally typed it. WOOPS. Quote Link to comment Share on other sites More sharing options...
skyer2000 Posted September 9, 2008 Author Share Posted September 9, 2008 And lol @ Sarah Palin and her horrid sense of humor. Fixed for ya And yes, only the first name. Quote Link to comment Share on other sites More sharing options...
DarkWater Posted September 9, 2008 Share Posted September 9, 2008 Uhh: <?php $string = 'John Doe, Sarah Palin, Joe Bidon, Barack "Omgcool" Obama'; $text = explode(',', $string); $text[0] = implode(',', array_reverse(explode(' ', $text[0]))); $string = implode(', ', $text); echo $string; ?> Quote Link to comment Share on other sites More sharing options...
skyer2000 Posted September 9, 2008 Author Share Posted September 9, 2008 Yeah I know its a pretty weird request, this string stuff is always confusing to me as well. Using the code changes "John McCain, Sarah Palin, Barack Obama" to "McCain,John, Sarah Palin, Barack Obama" I can't quite wrap my head around the code, how can I add a space there? Also, if it is just one name like "Sara Palin", it changes to ",Palin,Sarah". Any ideas? Quote Link to comment Share on other sites More sharing options...
DarkWater Posted September 9, 2008 Share Posted September 9, 2008 First of all, in my edit I fixed that space thing. I guess you caught it right before the edit (which I did pretty quickly, lol). Anyway, you never said just one name. Here: <?php $string = "Sarah Palin"; if (strpos($string, ',') !== FALSE) { $text = explode(',', $string); $text[0] = implode(',', array_reverse(explode(' ', $text[0]))); $string = implode(', ', $text); } else { $string = implode(', ', array_reverse(explode(' ', $string))); } echo $string; ?> EDIT: Syntax error, fixed. Quote Link to comment Share on other sites More sharing options...
skyer2000 Posted September 9, 2008 Author Share Posted September 9, 2008 Excellent work, thank you! Quote Link to comment Share on other sites More sharing options...
DarkWater Posted September 9, 2008 Share Posted September 9, 2008 No problem. 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.