Skip to content

Instantly share code, notes, and snippets.

@yyaremenko
Last active December 25, 2015 11:18
Show Gist options
  • Save yyaremenko/6967325 to your computer and use it in GitHub Desktop.
Save yyaremenko/6967325 to your computer and use it in GitHub Desktop.
<?php
/**
* Attempts to parse given meta tag's content from given html;
* deals with 'standard' and Open Graph meta tags.
*
* Order of meta tag attributes could be swapped around e.g. can either be
* name="..." content="..."
* or
* content="..." name="..."
*
* so we try to get meta tag content in 'swapped' way
* if we don't get in 'straight'
*
* @param string $html
* - html, which contains meta tags
* @param string $tagName
* - name of meta tag, e.g. 'description'
* @return null
*/
function getMetaTag($html, $tagName) {
$matches = array();
preg_match('/<meta.*?(name|property)=("|\')(og:)?' . $tagName . '("|\').*?content=("|\')(.*?)("|\')/i', $html, $matches);
if(isset($matches[6])) {
return trim($matches[6]);
}
preg_match('/<meta.*?content=("|\')(.*?)("|\').*?(name|property)=("|\')(og:)?' . $tagName . '("|\')/i', $html, $matches);
if(isset($matches[2])) {
return trim($matches[2]);
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment