Skip to content

Instantly share code, notes, and snippets.

@mokoshalb
Created January 5, 2018 10:08
Show Gist options
  • Save mokoshalb/6b6e7d15b4f4c06540735bfe071c3329 to your computer and use it in GitHub Desktop.
Save mokoshalb/6b6e7d15b4f4c06540735bfe071c3329 to your computer and use it in GitHub Desktop.
How to PHP regex match an HTML document's meta description
<?php
function parseDescription($html) {
// Get the 'content' attribute value in a <meta name="description" ... />
$matches = array();
// Search for <meta name="description" content="Buy my stuff" />
preg_match('/<meta.*?name=("|\')description("|\').*?content=("|\')(.*?)("|\')/i', $html, $matches);
if (count($matches) > 4) {
return trim($matches[4]);
}
// Order of attributes could be swapped around: <meta content="Buy my stuff" name="description" />
preg_match('/<meta.*?content=("|\')(.*?)("|\').*?name=("|\')description("|\')/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