Skip to content

Instantly share code, notes, and snippets.

@jeffreyvr
Last active June 22, 2020 18:27
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 jeffreyvr/f52589c471e8b8ec7cde7014275ea222 to your computer and use it in GitHub Desktop.
Save jeffreyvr/f52589c471e8b8ec7cde7014275ea222 to your computer and use it in GitHub Desktop.
OEmbed body parser for oscarotero/Embed.
<?php
use Exception;
use Embed\Embed;
class Oembed
{
/**
* Accepted Urls
*
* @var array Holds an array of URLs that are accepted to be replaced.
*/
public $acceptedUrls = [];
/**
* Constructor
*
* @return self
*/
public function __construct()
{
$this->acceptedUrls = [
'https://www.youtube.com',
'https://youtu.be',
'https://vimeo.com',
'https://twitter.com'
];
return $this;
}
/**
* Get the embed code by URL.
*
* @param string $url
* @return mixed
*/
public function getCodeByUrl($url)
{
try {
$embed = (new Embed)->get($url);
return $embed->code ?? null;
} catch(Exception $e) {
return $e->getMessage();
}
}
/**
* Find URLs inside a body and replace them with OEmbeds.
*
* @param string $body The body that needs to be parsed.
* @return string The parsed string.
*/
public function parse($body)
{
// @see https://stackoverflow.com/questions/35553751/javascript-regex-find-all-urls-outside-a-tags-nested-tags
return preg_replace_callback('/((http?|https?):\/\/[^"<\s]+)(?![^<>]*>|[^"]*?<\/a)/', function ($matches) {
$url = $matches[0];
foreach ($this->acceptedUrls as $domain) {
if (strpos($url, $domain, 0) !== false) {
return $this->getCodeByUrl($url);
}
}
return $url;
}, $body );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment