Don Alexander Eckford's REGEX Problem Solution

Problem

Extract the Social Security numbers from the following text. In other words, create a REGEX pattern to gather the following SS numbers and nothing else.

Name: Sam Parker
Phone: 517-333-1345
SS: 656-45-7752
Dr Lic: 345-678-123-456
Zip Code: 48910-3465

Name: Mary Parker
Phone: 517.333.1334
SS: 555-43-5743
Dr Lic: 333.478.646.233
Zip Code: 48910.3464

Name: Joe Spade
Phone: 517/289/0453
SS: 666-44-7770
Dr Lic: 123/456/789/001
Zip Code: 48910

Name: Matt Buds
Phone: 517 393 1556
SS: 567-66-4321
Dr Lic: 123 654 987 002
Zip Code: 48910 3457

Name: Karen Klutz
Phone: 517-393.1446
SS: 567-44-4321
Dr Lic: 123/654-987.002
Zip Code: 48910 3457

Extracted Social Security Numbers

 

CODE FOLLOWS

<?php
// Include header if necessary for your webpage
include('includes/header.php');
?>

<h1>Don Alexander Eckford's REGEX Problem Solution</h1>

<h4>Problem</h4>
<p>
    Extract the Social Security numbers from the following text. In other words, create a REGEX pattern
    to gather the following SS numbers and nothing else.
</p>

<pre>
Name: Sam Parker
Phone: 517-333-1345
SS: 656-45-7752
Dr Lic: 345-678-123-456
Zip Code: 48910-3465

Name: Mary Parker
Phone: 517.333.1334
SS: 555-43-5743
Dr Lic: 333.478.646.233
Zip Code: 48910.3464

Name: Joe Spade
Phone: 517/289/0453
SS: 666-44-7770
Dr Lic: 123/456/789/001
Zip Code: 48910

Name: Matt Buds
Phone: 517 393 1556
SS: 567-66-4321
Dr Lic: 123 654 987 002
Zip Code: 48910 3457

Name: Karen Klutz
Phone: 517-393.1446
SS: 567-44-4321
Dr Lic: 123/654-987.002
Zip Code: 48910 3457
</pre>

<h2>Extracted Social Security Numbers</h2>

<?php
// The input text containing the details
$text "
Name: Sam Parker
Phone: 517-333-1345
SS: 656-45-7752
Dr Lic: 345-678-123-456
Zip Code: 48910-3465

Name: Mary Parker
Phone: 517.333.1334
SS: 555-43-5743
Dr Lic: 333.478.646.233
Zip Code: 48910.3464

Name: Joe Spade
Phone: 517/289/0453
SS: 666-44-7770
Dr Lic: 123/456/789/001
Zip Code: 48910

Name: Matt Buds
Phone: 517 393 1556
SS: 567-66-4321
Dr Lic: 123 654 987 002
Zip Code: 48910 3457

Name: Karen Klutz
Phone: 517-393.1446
SS: 567-44-4321
Dr Lic: 123/654-987.002
Zip Code: 48910 3457
"
;

// Regex pattern to match Social Security numbers
// Explanation:
// - SSNs are in the format: ###-##-####
// - \d{3} matches exactly three digits
// - \d{2} matches exactly two digits
// - \d{4} matches exactly four digits
// - Combined, \d{3}-\d{2}-\d{4} matches SSNs
$regex "/\b\d{3}-\d{2}-\d{4}\b/";

// Use preg_match_all to extract all matches
preg_match_all($regex$text$matches);

// Check if matches were found
if (!empty($matches[0])) {
    echo 
"<ul>";
    foreach (
$matches[0] as $ssn) {
        
// Output each extracted SSN
        
echo "<li>$ssn</li>";
    }
    echo 
"</ul>";
} else {
    echo 
"<p>No Social Security numbers found.</p>";
}

// Include footer if necessary for your webpage
include('includes/footer.php');
?>