Hreflang Tag Generator — PHP source
Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* hreflang-tag-generator — pure locale-list validation + alternate-link
* emission (SEO/meta trio). Authored snippet mirroring src/lib/hreflang.ts:
* normalizeLocale + buildHreflang are a pure port of the TS grammar — the
* ll/ll-CC case-correcting locale rules, the row-located error strings,
* x-default appended last, and both output flavors (HTML <link> block and
* XML sitemap <xhtml:link> block, indentation and self-closing style
* included).
*/
declare(strict_types=1);
namespace CosmoDev\HreflangTagGenerator;
/** One locale/URL pair. Mirrors the TS HreflangRow interface. */
final class HreflangRow
{
public function __construct(
public string $locale,
public string $url,
) {
}
}
/** The field set for buildHreflang — rows plus an optional x-default URL. */
final class HreflangInput
{
/** @var HreflangRow[] */
public array $rows;
public function __construct(
array $rows = [],
public ?string $xDefaultUrl = null,
) {
$this->rows = $rows;
}
}
/** Diagnostics plus both emitted flavors. On failure ok is false, errors
* lists every row-located problem, and normalized/html/sitemap are empty —
* exactly like the TS result. */
final class HreflangResult
{
/**
* @param string[] $errors
* @param HreflangRow[] $normalized
*/
public function __construct(
public bool $ok,
public array $errors,
public array $normalized,
public string $html,
public string $sitemap,
) {
}
}
final class HreflangTagGenerator
{
/** ll (ISO-639-1 language) — two ASCII letters. */
private const SINGLE_RE = '/^([a-zA-Z]{2})$/';
/** ll-CC — two-letter language, two-letter region (ISO-3166). */
private const REGION_RE = '/^([a-zA-Z]{2})-([a-zA-Z]{2})$/';
/** http:// or https:// scheme prefix. */
private const URL_RE = '/^https?:\/\//';
/** Normalize a locale tag to Google's hreflang grammar: `ll` (ISO-639-1,
* lowercase) or `ll-CC` (region uppercase, ISO-3166). Case and surrounding
* whitespace are corrected (`en-us` -> `en-US`); anything else is invalid
* and returns null. The PHP twin of normalizeLocale() in
* src/lib/hreflang.ts — null stands in for the TS null. */
public static function normalizeLocale(string $raw): ?string
{
$t = trim($raw);
if (preg_match(self::SINGLE_RE, $t, $m) === 1) {
return strtolower($m[1]);
}
if (preg_match(self::REGION_RE, $t, $m) === 1) {
return strtolower($m[1]).'-'.strtoupper($m[2]);
}
return null;
}
/** Trim raw and return it when it starts with http:// or https://,
* otherwise null. Mirrors the TS validUrl() helper. */
private static function validUrl(string $raw): ?string
{
$t = trim($raw);
return preg_match(self::URL_RE, $t) === 1 ? $t : null;
}
/** Validate a locale/URL table and emit both hreflang flavors. Invalid
* input collects every error (row-located) and emits empty blocks; valid
* input normalizes locales, preserves row order, and appends x-default
* last. */
public static function buildHreflang(HreflangInput $input): HreflangResult
{
$errors = [];
$normalized = [];
$seen = [];
foreach ($input->rows as $i => $row) {
$n = $i + 1;
$locale = self::normalizeLocale($row->locale ?? '');
if ($locale === null) {
$errors[] = sprintf(
'Row %d: "%s" is not a valid locale — use ll or ll-CC (e.g. en, de-AT).',
$n,
trim($row->locale ?? '')
);
continue;
}
if (isset($seen[$locale])) {
$errors[] = sprintf('Row %d: locale "%s" is already used.', $n, $locale);
continue;
}
if (!isset($row->url) || trim($row->url) === '') {
$errors[] = sprintf('Row %d: URL is required.', $n);
continue;
}
$url = self::validUrl($row->url);
if ($url === null) {
$errors[] = sprintf('Row %d: URL must start with http:// or https://.', $n);
continue;
}
$seen[$locale] = true;
$normalized[] = new HreflangRow($locale, $url);
}
$xDefault = null;
$xd = $input->xDefaultUrl;
if ($xd !== null && trim($xd) !== '') {
$xDefault = self::validUrl($xd);
if ($xDefault === null) {
$errors[] = 'x-default: URL must start with http:// or https://.';
}
}
if (count($errors) > 0) {
return new HreflangResult(false, $errors, [], '', '');
}
$htmlLines = [];
$sitemapLines = [];
foreach ($normalized as $r) {
$htmlLines[] = sprintf(
'<link rel="alternate" href="%s" hreflang="%s" />',
$r->url,
$r->locale
);
$sitemapLines[] = sprintf(
' <xhtml:link rel="alternate" hreflang="%s" href="%s"/>',
$r->locale,
$r->url
);
}
if ($xDefault !== null) {
$htmlLines[] = sprintf(
'<link rel="alternate" href="%s" hreflang="x-default" />',
$xDefault
);
$sitemapLines[] = sprintf(
' <xhtml:link rel="alternate" hreflang="x-default" href="%s"/>',
$xDefault
);
}
return new HreflangResult(
true,
[],
$normalized,
implode("\n", $htmlLines),
implode("\n", $sitemapLines)
);
}
}
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 →