I worked on a few sites that stored authors / persons in the normal form of First Name - Last Name:

Thomas H. Hauk
Fuzzy Dunlop

but needed to sort or modify these names as "Dunlop, Fuzzy" or "D. Fuzzy" so they created separate CCK fields for first_name and last_name. This worked (especially for integration with views) but I reconfigured these fields as computed_field types to save data entry time.

For the first name, I used a quick strpos of everything in the title in front of the last word (presumably surname):

$node_field[0]['value'] = substr($node->title, 0, strrpos($node->title, " "));

For the last name, I used another regex to grab the

preg_match('~([^\s]+)(?:,.*)?$~',$node->title, $match);
$node_field[0]['value'] = $match[0];

Comments

Stolzenhain’s picture

This was extremely helpful!
What I realized though is, that during migration/copy&paste a lot of spaces slipped in titles, which broke the last name routine. I used the rtrim() command of PHP to remove spaces at the end:
just replace every instance of $node->title with rtrim($node->title) in the example above.

timothykc’s picture

Works great, but need to replace the term $node with $entity in D7.

timothykc’s picture

I've applied this technique to taxonomy terms as well.

In my case, the taxonomy had the format "firstname lastname"

Using Zualas' suggestion for pulling a term reference...

$entity_field[0]['value'] = taxonomy_term_title(taxonomy_term_load($entity->YOUR_FIELD['und'][0]['tid']));

...I input:

$entity_field[0]['value'] = preg_match('~([^\s]+)(?:,.*)?$~',taxonomy_term_title(taxonomy_term_load($entity->YOUR_FIELD['und'][0]['tid'])), $match);
$entity_field[0]['value'] = $match[0];

which displays "lastname"

timothykc’s picture

Here my problem was users with 'FIRSTNAME LASTNAME'

I want to pull lastname again (for sorting purposes):

$entity_field[0]['value'] = preg_match('~([^\s]+)(?:,.*)?$~',rtrim($entity->name), $match);
$entity_field[0]['value'] = $match[0];