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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Normalizing tokens before comparison lets you match messy input against a clean lookup list.
- 2Peeling known pieces off both ends of an array simplifies whatever ambiguous middle remains.
- 3Guarding each mutation with a count check keeps single-word and empty inputs from breaking the logic.
Related explainers
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
php
class TwoFactorController extends Controller { public function show(Request $request): View|RedirectResponse {
Two-factor auth challenge flow in Laravel
authentication
two-factor
middleware
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-a-full-name-into-components-in-php-explained-php-319a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.