Jump to content

adding target attribute based on domain


scvinodkumar

Recommended Posts

<?php
$source = '<a href="http://www.google.com/">test</a> and another <a href="http://test.com/dir/">test</a>';
function func_callback($matches) {
$return = '<a';
if (parse_url($matches[2], PHP_URL_HOST) == 'test.com') {
	$return .= ' target="_blank"';
}
return $return . $matches[1];
}
$source = preg_replace_callback('~<a\b([^>]*href=[\'"]([^\'"]*)[\'"][^>]*>)~i', 'func_callback', $source);
echo $source;
?>

 

Output:

<a href="http://www.google.com/">test</a> and another <a target="_blank" href="http://test.com/dir/">test</a>

Alternatively (based on thebadbad's solution):

 

$source = '<a href="http://www.google.com/">test</a> and another <a href="http://test.com/dir/">test</a>';
function func_callback($matches){
    if (parse_url($matches[1], PHP_URL_HOST) == 'test.com') {
$matches[0] = 'target="_blank" ' . $matches[0];
    }
    return $matches[0];
}

$source = preg_replace_callback('#href=[\'"]([^\'"]*)[\'"]#i', 'func_callback', $source);
echo htmlentities($source);

 

This way, we simplify the regex search, only resort to one capture (as opposed to two), and eliminate the $return variable.

This way, we simplify the regex search, only resort to one capture (as opposed to two), and eliminate the $return variable.

 

Yea, that's better. Think I kept in mind that the href attribute also appears within tags like base and link, but if the OP only runs the code on some body text, your simplified script will do just fine.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.