Way to complicated to do this with php in WordPress, I’d advice on doing this on the frontend with a bit of jquery magic. I wrote a tiny jQuery plugin that opens all external links (all links with another domain/host name than the current site) in a new window.
Check out the plugin:
https://www.npmjs.com/package/jquery.jold.external-hrefs
To do this manually, without the plugin is pretty simple too:
$('a').each(function() {
/** Get the current hostname */
var a = new RegExp("https://wordpress.stackexchange.com/" + window.location.host + "https://wordpress.stackexchange.com/");
/** Check if the href attribute of the link has a different hostname than the current site */
if( !a.test(this.href) ) {
$(this).on('click', function(event) {
event.preventDefault();
event.stopPropagation();
/** Create an url object for the link */
url = new URL(this.href);
/**
* Check if the links is a http protocol link
* otherwise just open all other link protocols (tel, mailto)
*/
if (url.protocol == 'http:' || url.protocol == 'https:') {
window.open(this.href, '_blank');
} else {
window.location.replace(this.href);
}
});
}
}