44 lines
1.2 KiB
PHP
44 lines
1.2 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Cf7stg;
|
|
|
|
final class DomainFormatter
|
|
{
|
|
public static function humanize(string $input): string
|
|
{
|
|
$input = trim($input);
|
|
if ($input === '') {
|
|
return '';
|
|
}
|
|
|
|
// Normalize: strip scheme, userinfo, path, query, fragment
|
|
$host = $input;
|
|
if (preg_match('#^[a-z][a-z0-9+\-.]*://#i', $host)) {
|
|
$parsed = parse_url($host);
|
|
$host = $parsed['host'] ?? $host;
|
|
}
|
|
// Strip any remaining path/query
|
|
$host = preg_replace('~[/?#].*$~', '', $host) ?? $host;
|
|
// Strip leading www.
|
|
$host = preg_replace('/^www\./i', '', $host) ?? $host;
|
|
|
|
if ($host === '') {
|
|
return '';
|
|
}
|
|
|
|
// Punycode → Unicode per label (.xn-- pieces may appear on only one side)
|
|
if (function_exists('idn_to_utf8') && strpos($host, 'xn--') !== false) {
|
|
$variant = defined('INTL_IDNA_VARIANT_UTS46')
|
|
? INTL_IDNA_VARIANT_UTS46
|
|
: 0;
|
|
$decoded = @idn_to_utf8($host, IDNA_DEFAULT, $variant);
|
|
if (is_string($decoded) && $decoded !== '') {
|
|
return $decoded;
|
|
}
|
|
}
|
|
|
|
return $host;
|
|
}
|
|
}
|