scvinodkumar Posted August 7, 2009 Share Posted August 7, 2009 How to add the 'target="_blank"' attribute in the <a> if the domain is test.com else no target Quote Link to comment Share on other sites More sharing options...
thebadbad Posted August 7, 2009 Share Posted August 7, 2009 <?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> Quote Link to comment Share on other sites More sharing options...
scvinodkumar Posted August 7, 2009 Author Share Posted August 7, 2009 thanks for your help, its working Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted August 7, 2009 Share Posted August 7, 2009 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. Quote Link to comment Share on other sites More sharing options...
thebadbad Posted August 7, 2009 Share Posted August 7, 2009 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. Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted August 7, 2009 Share Posted August 7, 2009 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.