Skip to content

Instantly share code, notes, and snippets.

@KOUISAmine
Created June 28, 2018 09:10
Show Gist options
  • Save KOUISAmine/460bdd2ab332b6e41f54d9dd24769052 to your computer and use it in GitHub Desktop.
Save KOUISAmine/460bdd2ab332b6e41f54d9dd24769052 to your computer and use it in GitHub Desktop.
<?php
function getCdnUrls($html)
{
$cdnUrl = "//cdn.mon-domain.com";
$baseUrl = "mon-domain.com";
$patterns = [
// Match sources that are from the www or mobile urls
// We check for the schema as well as protocol relative urls
'~(<(img|script|link)[^>]*)(src|href) *= *(["\'])(https?:)?//(' . preg_quote($baseUrl) . ')~',
// Match sources that just begin relative to the current domain
// Our regex matches the initial "/" character with a negative lookahead
// ensuring the next character is not a slash
'~(<(img|script|link)[^>]*)(src|href) *= *(["\'])/(?!/)~'
];
return $html = preg_replace_callback($patterns, function (array $matches) use ($cdnUrl) {
return $matches[1] . $matches[3] . "=" . $matches[4] . $cdnUrl;
}, $html);
}
//Call the function to get your CDN URL:
$html = '<img src="https://mon-domain.com/logo.png" />';
echo getCdnUrls($html);
// you will get it
// <img src="//cdn.mon-domain.com/logo.png" />
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment