Created
November 1, 2016 16:09
-
-
Save onigetoc/aefd26173d7b7316ffa9e4891e60ef0f to your computer and use it in GitHub Desktop.
How to PHP regex match an HTML document's declared favicon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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