PHP Function to Force Links to Open in a New Window

Here’s a very simple PHP function that will parse text and force fully constructed links to open in a new window. If you’re building a comment area (or something similar) for your website it’s likely that you want to retain an open page to minimise your click-through-rate, and this function will assist to serve that purpose.

If you are parsing plain text links it’s likely that you will want to use the “make your links clickable” function and adjust it accordingly (on line 15 simple add target=”_blank” into the link structure).

<?php
function newwin($text) {
	$text = preg_replace('/<a (. ?)>/i', "<a $1 target='_blank' rel='external'>", $text);
	return $text;
}

$content = "<a href=\"http://www.internoetics.com\">This link</a> will open in a new window";
echo newwin($content);
?>

If you liked this article, you may also like:

  1. Make text links clickable
  2. Automatically Convert MP3 links to Audio Players
  3. Break links into two halves separated by dots with PHP
  4. Force the Download of a File with PHP
  5. PHP function to truncate text (into a preview or excerpt) with trailing dots…
About Marty

is a passionate web developer from Sydney, Australia. He owns about 400 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. You can follow Marty on Twitter or Google+.

Speak Your Mind

*