How to extract attributes from an HTML string in PHP (without using RegEx)

Say you have an <a>, <link> or other HTML element and you need to extract its href (or other) attribute. You can extract those values using DOMDocument quite easily:

$custom_font = '<link href="[email protected];700&display=swap" rel="stylesheet">';

$link = $custom_font;
$dom = new DOMDocument();
foreach ($dom->getElementsByTagName("link") as $a) {
    echo $a->getAttribute("href");

Leave a Reply

Your email address will not be published.