Skip to content

PII Redactor — PHP source

Paste text and automatically detect and mask personal data — emails, phone numbers, IP addresses, SSNs, credit card numbers, and dates.

This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
/**
 * pii-redactor — PII detection & redaction (email, phone, IPs, SSN, cards, dates).
 *
 * Language: PHP 7.4+ (standard library only).
 * CosmoDev polyglot showcase port of the `pii-redactor` tool, ported from
 * src/lib/pii-redactor.ts (the canonical TypeScript implementation).
 *
 * PCRE drives the candidate scan (lookbehind/lookahead guards included);
 * every candidate still passes the same structural validator as the
 * TypeScript reference (octet ranges, Luhn checksum, month/day bounds,
 * E.164 digit count), and overlaps resolve by type priority. Never throws.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

/** All PII types, in display order. */
const PII_TYPES = ['email', 'phone', 'ipv4', 'ipv6', 'ssn', 'credit-card', 'date'];

/**
 * Luhn checksum. `$digits` must be a non-empty string of 0-9 (any
 * separators make it invalid - strip them first). Returns false otherwise.
 */
function isValidLuhn(string $digits): bool
{
    if (preg_match('/^\d+$/', $digits) !== 1) {
        return false;
    }
    $sum = 0;
    $double = false;
    for ($i = strlen($digits) - 1; $i >= 0; $i--) {
        $d = ord($digits[$i]) - 48;
        if ($double) {
            $d *= 2;
            if ($d > 9) {
                $d -= 9;
            }
        }
        $sum += $d;
        $double = !$double;
    }
    return $sum % 10 === 0;
}

// --- Per-type structural validators (regex candidates pass through these) ---

/** Octets 0-255 each; the regex already bounds the shape to a dotted quad. */
function piiIsValidIpv4(string $c): bool
{
    foreach (explode('.', $c) as $octet) {
        if ((int) $octet > 255) {
            return false;
        }
    }
    return true;
}

/** Full 8-group form, or a compressed `::` form expanding to exactly 8. */
function piiIsValidIpv6(string $c): bool
{
    if (preg_match('/[A-Fa-f0-9]/', $c) !== 1) {
        return false; // lone ":" / "::" (URL scheme separators) carry no hex digits
    }
    $groups = explode(':', $c);
    if (!in_array('', $groups, true)) {
        if (count($groups) !== 8) {
            return false;
        }
        foreach ($groups as $g) {
            if (preg_match('/^[A-Fa-f0-9]{1,4}$/', $g) !== 1) {
                return false;
            }
        }
        return true;
    }
    $parts = explode('::', $c); // compressed: at most one "::", sides hold < 8 groups
    if (count($parts) > 2) {
        return false;
    }
    $left = $parts[0] !== '' ? explode(':', $parts[0]) : [];
    $right = (count($parts) > 1 && $parts[1] !== '') ? explode(':', $parts[1]) : [];
    if (count($left) + count($right) > 7) {
        return false;
    }
    foreach (array_merge($left, $right) as $g) {
        if (preg_match('/^[A-Fa-f0-9]{1,4}$/', $g) !== 1) {
            return false;
        }
    }
    return true;
}

/** ISO calendar plausibility: month 01-12, day 01-31. */
function piiIsValidDate(string $c): bool
{
    if (preg_match('/^\d{4}-(\d{2})-(\d{2})$/', $c, $m) !== 1) {
        return false;
    }
    return $m[1] >= '01' && $m[1] <= '12' && $m[2] >= '01' && $m[2] <= '31'; // 2-digit lexicographic
}

/** E.164 digit budget (7-15) and structural guards for the fuzzy phone shape. */
function piiIsValidPhone(string $c): bool
{
    $digits = preg_replace('/\D/', '', $c);
    if (strlen($digits) < 7 || strlen($digits) > 15) {
        return false;
    }
    // IP-shaped (already claimed by ipv4) and date-shaped spans are never phones.
    return preg_match('/^\d{1,3}(?:\.\d{1,3}){3}$/', $c) !== 1
        && preg_match('/^\d{4}-\d{2}-\d{2}$/', $c) !== 1;
}

/** 13-19 digits with optional space/dash grouping, plus a Luhn checksum. */
function piiIsValidCard(string $c): bool
{
    $digits = preg_replace('/\D/', '', $c);
    return strlen($digits) >= 13 && strlen($digits) <= 19 && isValidLuhn($digits);
}

// --- Detectors: a global candidate regex + an optional structural validator.
// Array order IS the overlap priority (index 0 claims spans first).

/**
 * @return array<int, array{type: string, re: string, validate: ?callable}>
 */
function piiDetectors(): array
{
    return [
        ['type' => 'email', 're' => '/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/'],
        ['type' => 'credit-card', 're' => '/\d(?:[ -]?\d){11,}/', 'validate' => 'piiIsValidCard'],
        ['type' => 'ssn', 're' => '/\b\d{3}-\d{2}-\d{4}\b/'],
        ['type' => 'ipv6', 're' => '/(?<![:\w])[A-Fa-f0-9]{0,4}(?::[A-Fa-f0-9]{0,4}){1,7}(?![:\w])/', 'validate' => 'piiIsValidIpv6'],
        ['type' => 'ipv4', 're' => '/(?<![\w.])(?:\d{1,3}\.){3}\d{1,3}(?!\.?\d)(?!\w)/', 'validate' => 'piiIsValidIpv4'],
        ['type' => 'date', 're' => '/(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)/', 'validate' => 'piiIsValidDate'],
        // Fuzziest pattern - lowest priority: optional +country, optional
        // (area), then 1-4 groups of 2-4 digits separated by spaces, dashes, dots.
        ['type' => 'phone', 're' => '/(?<![\d(])(?:\+\d{1,3}[ .-]?)?(?:\(\d{1,4}\)|\d{1,4})(?:[ .-]?\d{2,4}){1,4}(?!\d)/', 'validate' => 'piiIsValidPhone'],
    ];
}

/**
 * Detect personal data in `$text`. Pass `$types` to scan for a subset (the
 * per-type toggles); pass null to scan for everything. Returns matches in
 * document order, non-overlapping, with exact `start`/`end` byte offsets.
 *
 * @return array<int, array{type: string, start: int, end: int, original: string}>
 */
function detectPii(string $text, ?array $types = null): array
{
    $source = $text ?? '';
    $candidates = [];
    foreach (piiDetectors() as $index => $det) {
        if ($types !== null && !in_array($det['type'], $types, true)) {
            continue;
        }
        if (preg_match_all($det['re'], $source, $matches, PREG_OFFSET_CAPTURE) !== false) {
            foreach ($matches[0] as [$match, $offset]) {
                if ($match === '') {
                    break; // zero-length safety
                }
                $validate = $det['validate'] ?? null;
                if ($validate === null || $validate($match)) {
                    $candidates[] = ['type' => $det['type'], 'p' => $index, 'start' => $offset, 'end' => $offset + strlen($match), 'original' => $match];
                }
            }
        }
    }
    // Highest-priority (lowest index) candidates claim their span first.
    usort($candidates, fn (array $a, array $b): int => $a['p'] <=> $b['p'] ?: $a['start'] <=> $b['start']);
    $kept = [];
    foreach ($candidates as $c) {
        $overlap = false;
        foreach ($kept as $k) {
            if ($c['start'] < $k['end'] && $k['start'] < $c['end']) {
                $overlap = true;
                break;
            }
        }
        if (!$overlap) {
            $kept[] = $c;
        }
    }
    usort($kept, fn (array $a, array $b): int => $a['start'] <=> $b['start']);
    return array_map(fn (array $m): array => ['type' => $m['type'], 'start' => $m['start'], 'end' => $m['end'], 'original' => $m['original']], $kept);
}

/**
 * Redact personal data from `$text`, replacing every detected span with
 * `$options['mask']` (default '[REDACTED]'). Accepts the same `$options['types']`
 * subset as detectPii.
 */
function redactPii(string $text, array $options = []): string
{
    $source = $text ?? '';
    $mask = $options['mask'] ?? '[REDACTED]';
    $matches = detectPii($source, $options['types'] ?? null);
    $out = $source;
    for ($i = count($matches) - 1; $i >= 0; $i--) {
        $m = $matches[$i];
        $out = substr($out, 0, $m['start']) . $mask . substr($out, $m['end']); // right-to-left keeps indices valid
    }
    return $out;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →