Last active
          May 1, 2025 17:38 
        
      - 
      
- 
        Save james2doyle/4d0330fdf780cb5e41a0b90d689fb36d to your computer and use it in GitHub Desktop. 
Revisions
- 
        james2doyle revised this gist May 1, 2025 . 1 changed file with 12 additions and 0 deletions.There are no files selected for viewingThis 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 charactersOriginal file line number Diff line number Diff line change @@ -1,5 +1,17 @@ <?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 
- 
        james2doyle created this gist May 1, 2025 .There are no files selected for viewingThis 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,29 @@ <?php 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(); } }