Last active
May 1, 2025 17:38
-
-
Save james2doyle/4d0330fdf780cb5e41a0b90d689fb36d to your computer and use it in GitHub Desktop.
A helper function for Laravel that can add missing target blank to HTML so that external links open in a new tab
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!function_exists('is_external_url')) { | |
/** | |
* Check if a URL is external | |
*/ | |
function is_external_url(string $url) | |
{ | |
$test = str(config('app.url'))->basename()->prepend('*')->append('*')->toString(); | |
return str($url)->is($test, true) === false; | |
} | |
} | |
if (!function_exists('add_target_blank_to_external_links')) { | |
/** | |
* Takes in an HTML string and makes sure that any external URLs are marked as target blank | |
*/ | |
function add_target_blank_to_external_links(string|\Illuminate\Support\Stringable $escapedHtml) | |
{ | |
$html = stripslashes($escapedHtml); | |
$doc = new \DOMDocument(); | |
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); | |
$xpath = new \DOMXPath($doc); | |
/** @var \DOMElement */ | |
$links = $xpath->query('//a[@href]'); | |
foreach ($links as $link) { | |
$href = $link->attributes->getNamedItem('href')->value; | |
if (\Illuminate\Support\Facades\URL::isValidUrl($href) && is_external_url($href)) { | |
$link->setAttribute('target', '_blank'); | |
$link->setAttribute('rel', 'noopener'); | |
} | |
} | |
return str($doc->saveHTML())->toHtmlString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment