php 51 lines · 8 steps

Parsing a full name into components in PHP

A parser peels titles and suffixes off a name, then splits the rest into first, middle, and last.

Explained by highlit
1<?php
2 
3class NameParser
4{
5 private const TITLES = [
6 'mr', 'mrs', 'ms', 'miss', 'dr', 'prof', 'rev', 'sir', 'madam',
7 ];
8 
9 private const SUFFIXES = [
10 'jr', 'sr', 'ii', 'iii', 'iv', 'v', 'phd', 'md', 'esq',
11 ];
12 
13 public function parse(string $fullName): array
14 {
15 $parts = preg_split('/\s+/', trim($fullName), -1, PREG_SPLIT_NO_EMPTY);
16 
17 $result = [
18 'title' => null,
19 'first' => null,
20 'middle' => null,
21 'last' => null,
22 'suffix' => null,
23 ];
24 
25 if (empty($parts)) {
26 return $result;
27 }
28 
29 $normalize = static fn (string $word): string => rtrim(strtolower($word), '.');
30 
31 if (count($parts) > 1 && in_array($normalize($parts[0]), self::TITLES, true)) {
32 $result['title'] = array_shift($parts);
33 }
34 
35 if (count($parts) > 1 && in_array($normalize(end($parts)), self::SUFFIXES, true)) {
36 $result['suffix'] = array_pop($parts);
37 }
38 
39 $result['first'] = array_shift($parts);
40 
41 if (!empty($parts)) {
42 $result['last'] = array_pop($parts);
43 }
44 
45 if (!empty($parts)) {
46 $result['middle'] = implode(' ', $parts);
47 }
48 
49 return $result;
50 }
51}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Normalizing tokens before comparison lets you match messy input against a clean lookup list.
  2. 2Peeling known pieces off both ends of an array simplifies whatever ambiguous middle remains.
  3. 3Guarding each mutation with a count check keeps single-word and empty inputs from breaking the logic.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing a full name into components in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code