tobeyt23 Posted September 7, 2007 Share Posted September 7, 2007 I what to replace/append a href link with target='_blank' within a string. I am have trouble getting this to work: <?php $text = '<p>This needs to work: <a href="http://www.cnn.com">This is a link</a></p>'; $text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\" target=\"_blank\">\\0</a>", $text); echo $text; ?> Quote Link to comment Share on other sites More sharing options...
effigy Posted September 7, 2007 Share Posted September 7, 2007 <pre> <?php function change_target($match) { $a_tag = $match[0]; if (strpos($a_tag, 'target') == FALSE) { return preg_replace('/(?=>)/', ' target="_blank"', $a_tag); } else { return preg_replace('/(?<=target=)(["\'])?(?(1).+?\1|\S+)/', '"_blank"', $a_tag); } } $text = '<p>This needs to work: <a href="http://www.cnn.com">This is a link</a></p>'; echo preg_replace_callback('/<a[^>]+>/', 'change_target', $text); $text = '<p>This needs to work: <a target=somewhere_else href="http://www.cnn.com">This is a link</a></p>'; echo preg_replace_callback('/<a[^>]+>/', 'change_target', $text); ?> </pre> Quote Link to comment Share on other sites More sharing options...
tobeyt23 Posted September 7, 2007 Author Share Posted September 7, 2007 Sweet that is exactly what I needed! Quote Link to comment Share on other sites More sharing options...
effigy Posted September 7, 2007 Share Posted September 7, 2007 On second thought... if (strpos($a_tag, 'target') == FALSE) { ...should be... if (strpos($a_tag, ' target=') == FALSE) { ...just in case the URL has the word "target" in it. Quote Link to comment Share on other sites More sharing options...
tobeyt23 Posted September 21, 2007 Author Share Posted September 21, 2007 How would i do this to check if http:// is added to the link? Quote Link to comment Share on other sites More sharing options...
effigy Posted September 21, 2007 Share Posted September 21, 2007 Are you trying to add it if it's not there? <pre> <?php function change_target($match) { $a_tag = $match[0]; if (strpos($a_tag, 'target') == FALSE) { $a_tag = preg_replace('/(?=>)/', ' target="_blank"', $a_tag); } else { $a_tag = preg_replace('/(?<=target=)(["\'])?(?(1).+?\1|\S+)/', '"_blank"', $a_tag); } ### Add http:// if it's missing. return preg_replace('#(?<=href=)(?(?=["\'])(["\']))(?!http://)#', '\1http://', $a_tag); } $text = '<p>This needs to work: <a href="www.cnn.com">This is a link</a></p>'; echo preg_replace_callback('/<a[^>]+>/', 'change_target', $text); $text = '<p>This needs to work: <a target=somewhere_else href="http://www.cnn.com">This is a link</a></p>'; echo preg_replace_callback('/<a[^>]+>/', 'change_target', $text); ?> </pre> 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.