Skip to content

Instantly share code, notes, and snippets.

@onigetoc
Created November 1, 2016 16:09
Show Gist options
  • Save onigetoc/aefd26173d7b7316ffa9e4891e60ef0f to your computer and use it in GitHub Desktop.
Save onigetoc/aefd26173d7b7316ffa9e4891e60ef0f to your computer and use it in GitHub Desktop.
How to PHP regex match an HTML document's declared favicon
<?php
function parseFavicon($html) {
// Get the 'href' attribute value in a <link rel="icon" ... />
// Also works for IE style: <link rel="shortcut icon" href="http://www.example.com/myicon.ico" />
// And for iOS style: <link rel="apple-touch-icon" href="somepath/image.ico">
$matches = array();
// Search for <link rel="icon" type="image/png" href="http://example.com/icon.png" />
preg_match('/<link.*?rel=("|\').*icon("|\').*?href=("|\')(.*?)("|\')/i', $html, $matches);
if (count($matches) > 4) {
return trim($matches[4]);
}
// Order of attributes could be swapped around: <link type="image/png" href="http://example.com/icon.png" rel="icon" />
preg_match('/<link.*?href=("|\')(.*?)("|\').*?rel=("|\').*icon("|\')/i', $html, $matches);
if (count($matches) > 2) {
return trim($matches[2]);
}
// No match
return null;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment