Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active May 1, 2025 17:38
Show Gist options
  • Save james2doyle/4d0330fdf780cb5e41a0b90d689fb36d to your computer and use it in GitHub Desktop.
Save james2doyle/4d0330fdf780cb5e41a0b90d689fb36d to your computer and use it in GitHub Desktop.

Revisions

  1. james2doyle revised this gist May 1, 2025. 1 changed file with 12 additions and 0 deletions.
    12 changes: 12 additions & 0 deletions add_target_blank_to_external_links.php
    Original 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
  2. james2doyle created this gist May 1, 2025.
    29 changes: 29 additions & 0 deletions add_target_blank_to_external_links.php
    Original 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();
    }
    }