Community Documentation

Extract First / Last Name from Title

Last updated August 26, 2009. Created by schnippy on August 26, 2009.
Log in to edit this page.

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

This was extremely

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.

One addition for D7

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

Extracting part of a taxonomy term

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"

Extracting part of a USER PROFILE Title

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];

Page status

No known problems

Log in to edit this page

About this page

Drupal version
Drupal 5.x, Drupal 6.x, Drupal 7.x
Audience
Developers and coders

Site Building Guide

Drupal’s online documentation is © 2000-2012 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.
nobody click here