First name after comma

I have a variable with the following:
“Last Name, First Name” (without quotation marks and at times, there may be a middle initial in the following form: N. (period included)

I need to take this variable and swap the last and first name to be in the following form:
“First Name N. Last Name” (without quotation marks)

I thought that using preg_match would do the trick, but I soon realized that a few string functions would be more efficient. Either way, I’ve been unable to decipher how to do this due to my lack of knowledge with string functions.

No need to do leg work, but if someone could at least point me in the right direction, I would appreciate it (i.e. - using substr, what other functions might I need to accomplish this, etc.)

If names are always in that exact format you can use


$name='Last Name, First Name';
echo implode(' ', array_reverse(explode(', ', $name)));

Can’t you just split it off by the comma? Or are you trying to put the various values into a database?

Geez… I was way off. Here’s what I had (please don’t laugh!):

preg_match("/,(.*)/",$name,$match);
$first_name = $match[1];
$last_name = substr(strrev(strstr(strrev($clean_peer_evaluator), strrev(','))), 0, -strlen(','));
$clean_peer_evaluator = $first_name.' '.$last_name;

I mean, I guess it got the job done, but I wish I could see the better ways like you did in your last post, Scallio… Anyway, that got it. Thanks!

Can’t you just split it off by the comma?

What would be the best way? I can’t seem to understand what specific approach I should use with “grabbing everything after the comma” and “grabbing everything before the comma.” I’m not using a database with this.