typestar

link_checker.php in PHP

Pulls every href out of an HTML string and buckets the link styles.

<?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";

How it works

  1. preg_match_all captures each href attribute from the markup.
  2. A preg_match on https?:// marks a link as absolute.
  3. Leading / or ./ marks it relative; anchors and mailto are other.
  4. The report counts each bucket and lists what landed in it.

Keywords and builtins used here

The run, in numbers

Lines
40
Characters to type
992
Tokens
194
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 129 seconds.

Type this snippet

Step 3 of 3 in Encore, step 27 of 27 in Language basics.

← Previous