tags:

views:

77

answers:

4

If I wanted to take a first name / last name string separated by a comma and change the order, how might I go about that?

last name, firstname

should be changed to

firstname lastname (without the comma)

Thanks.

A: 

Something like this would work:

string[] names = LastNameFirstName.Split(',');
string FirstNameLastName = names[1] + " " + names[0];
Andrew Siemer
Argh...php! I posted C#...<GRIN>
Andrew Siemer
People should really say what language they are asking about rather then relying on people to look at their tags.
Kane Wallmann
It's ok, I can still follow the logic in it. I think PHP has a split function that does the same thing. It's a start in the right direction, thanks!
split() uses a RegExp which is a bit overkill... explode() would be more effective.
Kane Wallmann
Thanks Kane. Much appreciated. Gonna give you credit for the answer too. :)
+4  A: 

This should do it.

   $string = 'last,first';
   list($last,$first) = explode( ",", $string );
   echo $first . ' ' . $last;
Kane Wallmann
You should probably use `explode(",", $string, 2)` just in case there is a 2nd comma.
too much php
+2  A: 

If you wanted to get it done in a spiffy one-liner you could do this:

<?php
$name = "Smith, Dave";
echo implode(' ', array_reverse(explode(',', $name)));
hobodave
You are adding unnecessary overhead to the equation for the sake of saving 1 line. This way is also harder for someone who hasn't seen it to figure out what it does. What is the advantage to this?
Kane Wallmann
The question was neither: "How do I do X in the fastest way possible?", nor "How do I do X with the smallest memory footprint possible?". Thus, I provided a solution.
hobodave
hobodave I didn't mean to offend I simply didn't understand why you would want to sacrifice efficiency and readability for the sake of one line. Sorry for coming across rude.
Kane Wallmann
None taken. I apologize for my snippy retort. It's a programming style thing really. Would I do that in my own code? Maybe, maybe not. I'd definitely wrap it in a method though, and not worry about the inner-workings or performance of it until profiling time came. e.g. $foo->normalizeNameFirstLast('Smith, Dave'); I'm a big proponent of avoiding premature optimization. From a readability standpoint, you definitely have an argument though.
hobodave
A: 
$string = 'last ,  first';
list($last,$first) = preg_split("/\s+,\s+/",$string); 
$s = preg_split("/[, ]/",$string);   
print implode(" ", array($s[0], end($s)));
print implode(" ", array($last,$first));
print preg_replace("/(\w+)\s+,\s+(\w+)/","$2 $1", $string);
ghostdog74