9 11 Votes

PHP: Add target="_blank" to (outgoing) HTML Links

Tip by Stefan Trost | 03/02/2013 at 15:41

In this tip, I show you a PHP solution to add the attribute target="_blank" to all (outgoing) links automatically. This code can be used, for example, to edit a text that a user has entered into a comment form automatically and to ensure that all links will open in a new window or tab.

Add attribut target="_blank" to all links

We make use of the PHP function preg_replace, which we feed with the following regular expression:

$l='<a href="https://www.sttmedia.com">';

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

echo $l;  // <a href="https://www.sttmedia.com" target="_blank">

So, we are searching for a link construct  beginning with '<a href' and ending with '">' and we are replacing this construct with the matching string including 'target="_blank"'.

Add attribute target="_blank" only to outgoing links

Assuming all outgoing links are starting with "http" while internal links are not containing the full domain name and are something like "/internalpage.html" instead, we can expand our code in the following way:

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

With this, the attribute will only be added to links referring to another website than the own one. As long as the visitors are browsing within the own domain, it is always used the current browser windows. As soon as they are going to leave the own domain, a new browser window is opened.


About the Author

Avatar AuthorYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile | Message


Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own articles on askingbox.com. How to do.