Regexp hyperlink
| From: | Martin Visser | Date: | Sun, 18 Apr 2004 20:08:51 +0000 |
| Subject: | Regexp hyperlink | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-183780@lists.php.net to get a copy of this message | ||
I can't figure out how to do this.
I've four different methods for changing a piece of text into a hyperlink.
the text:
[link=www.hotmail.com]hotmail[/link] [link=http://www.hotmail.com]hotmail[/link] www.hotmail.com http://www.hotmail.com
what it should become (offcourse in HTML it will change to a real hyperlink):
<a href="http://www.hotmail.com" target="_blank">hotmail</a> <a href="http://www.hotmail.com" target="_blank">hotmail</a> <a href="http://www.hotmail.com" target="_blank">www.hotmail.com</a> <a href="http://www.hotmail.com" target="_blank">http://www.hotmail.com</a>
i've got this regexps, at this point there are two different ones and I would like to combine them (not really necessary):
1.
$text = str_replace("[link=http://", "[link=", $text);
$text = preg_replace("/\[link=(.+)\](.+)\[\/link\]/U", "<a href=\"http://\\1\" target=\"_blank\">\\2</a>", $text);
2.
$text = preg_replace("!(((http(s?)://)|(www|home\.))([-a-z0-9.]{2,}\.[a-z]{2,4}(:[0-9]+)?)((/([^\s]*[^\s.,\"'])?)?)((\?([^\s]*[^\s.,\"'])?)?))!i", "<a href=\"http\\4://\\5\\6\\8\\9\" target=\"_blank\">\\1</a>", $text); // I copied this one, maybe someone knows a better one?
the problem is that it's replaced a second time resulting in this:
<a href="<a href="http://www.hotmail.com target="_blank">http://www.hotmail.com</a>]hotmail[/link] [link=<a href="http://www.hotmail.com" target="_blank">www.hotmail.com</a>" target="_blank">hotmail</a> <a href="http://www.hotmail.com" target="_blank">www.hotmail.com</a> <a href="http://www.hotmail.com" target="_blank">http://www.hotmail.com</a>
the last two (without the [link=] part) are working