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
https://forums.phpfreaks.com/topic/68394-ereg_replace-help/
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
https://forums.phpfreaks.com/topic/68394-ereg_replace-help/#findComment-343862
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
https://forums.phpfreaks.com/topic/68394-ereg_replace-help/#findComment-352372
Share on other sites

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.