MajAfy
MajAfy

Reputation: 3097

Add target=_blank to outside links

I want to add target="_blank" to <a> tags to open that link in a new page, so I found this RegEx :

$content = preg_replace('/(<a href[^<>]+)>/is', '\\1 target="_blank">', $content);

This will work without any problem, but this code will add target="_blank" to all links, I want to add just to links which href will start with http://

How can I do this?

Upvotes: 2

Views: 1964

Answers (2)

hwnd
hwnd

Reputation: 70732

You've asked for a regular expression here, but it's not the right tool for the job.

$doc = new DOMDocument;
$doc->loadHTML($html); // Load your HTML

$xpath = new DOMXPath($doc);
$links = $xpath->query('//a[starts-with(@href, "http://")]');

foreach($links as $link) { 
   $link->setAttribute('target', '_blank');
}

echo $doc->saveHTML();

If you want to exclude internal links as suggested in the comments, you can do:

$links = $xpath->query('//a[starts-with(@href, "http://") and 
                        not(starts-with(@href, "http://yoursite.com")) and
                        not(starts-with(@href, "http://www.yoursite.com))]');

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626920

You can use this regex:

(<a\b[^<>]*href=['"]?http[^<>]+)>

See demo.

I have added \b[^<>]* to account for any other attributes before href.

Sample code:

$re = "/(<a\\b[^<>]*href=['\"]?http[^<>]+)>/is"; 
$str = "<a href=\"do.com\">\n<a href=\"do.com\">\n<a another=\"val\" href=\"http://do.com\">\n"; 
$subst = "$1 target=\"_blank\">"; 
$result = preg_replace($re, $subst, $str);

Upvotes: 0

Related Questions