Jump to content

ereg_replace Help


tobeyt23

Recommended Posts

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;

?> 

Link to comment
Share on other sites

<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>

Link to comment
Share on other sites

  • 2 weeks later...

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>

Link to comment
Share on other sites

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.