Skip to content

Instantly share code, notes, and snippets.

@Zegnat
Created February 20, 2015 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zegnat/c5d4247dd7aa955dc9f1 to your computer and use it in GitHub Desktop.
Save Zegnat/c5d4247dd7aa955dc9f1 to your computer and use it in GitHub Desktop.
//phrase image and youtube links
foreach ($template->query('//article/div/p[a and count(*)=1 and not(normalize-space(text()))]') as $node) {
$link = trim($node->nodeValue);
$replace = false;
if (
preg_match('~(?:
https?://(?:www\.)?youtu(?:be\.com/(?:embed/|watch\?(?:.+&)?v=)|\.be/)([a-z0-9_\-]+) # Parsing YouTube URLs.
|
(.+\.(?:png|jpe?g|gif|webp)$) # Parsing image URLs.
|
(.+\.(?:webm|mp4|mov|3gp|avi)$) # Parsing video URLs.
)~ixA', $link, $matches)
) {
if (strlen($matches[1])) { // We found a YouTube video.
$replace = '<iframe width="100%" height="360" src="http://www.youtube-nocookie.com/embed/' . $matches[1] . '?autoplay=0&amp;rel=0" frameborder="0" allowfullscreen="allowfullscreen">' . safeHTML($link) . '</iframe>';
} else if (strlen($matches[2])) { // We found an image link.
$replace = '<a target="_blank" href="' . safeHTML($link) . '"><img style="max-width: 100%;" src="' . $matches[2] . '" alt="Click to view full size image." /></a>';
} else if (strlen($matches[3])) { // We found an video link.
$replace = '<video style="max-width: 100%;" src="' . $matches[3] . '" controls="controls" />';
}
}
if ($replace) {
$frag = $node->ownerDocument->createDocumentFragment();
if (!@$frag->appendXML($replace) || !@$node->parentNode->replaceChild($frag, $node)) {
throw new Exception("Invalid HTML");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment