Jump to content

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.

Yeah, I thought about tags like that (link, base, area, etc..) afterwards.. not sure if there would be adverse effects on those (never tested that to be honest). For anchor tags specifically, yours would do just nicely :)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.