typestar

link_checker.php en PHP

Extrae cada href de una cadena HTML y agrupa los enlaces por estilo.

<?php
// link_checker: sort the hrefs in a page into absolute and relative

$html = <<<HTML
<nav>
  <a href="https://example.com/docs">Docs</a>
  <a href="/pricing">Pricing</a>
  <a href="./guide/intro.html">Guide</a>
  <a href="https://status.example.com">Status</a>
  <a href="#features">Features</a>
  <a href="mailto:team@example.com">Contact</a>
</nav>
HTML;

preg_match_all('/href="([^"]+)"/', $html, $matches);
$links = $matches[1];

$absolute = [];
$relative = [];
$other = [];
foreach ($links as $href) {
    if (preg_match('#^https?://#', $href)) {
        $absolute[] = $href;
    } elseif ($href[0] === '/' || str_starts_with($href, './')) {
        $relative[] = $href;
    } else {
        $other[] = $href;
    }
}

echo "links found: ", count($links), "\n";
echo "absolute (", count($absolute), "):\n";
foreach ($absolute as $href) {
    echo "  ", $href, "\n";
}
echo "relative (", count($relative), "):\n";
foreach ($relative as $href) {
    echo "  ", $href, "\n";
}
echo "other (", count($other), "): ", implode(", ", $other), "\n";

Cómo funciona

  1. preg_match_all captura cada atributo href del marcado.
  2. Un preg_match sobre https?:// marca un enlace como absoluto.
  3. Un / o ./ inicial lo marca como relativo; anclas y mailto son otros.
  4. El reporte cuenta cada grupo y lista lo que cayó en él.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
40
Caracteres a escribir
992
Tokens
194
Ritmo de tres estrellas
90 tpm

Al ritmo de tres estrellas de 90 tokens por minuto, este intento toma unos 129 segundos.

Escribe este fragmento

Paso 3 de 3 en Bis; paso 27 de 27 en Fundamentos del lenguaje.

← Anterior