Bug 1 I couldn't reproduce, could you post again if it still occurs using my example?
Bug 2: It can be done, though it's fairly complicated. I use urls beginning with http:// as example.
1)
Put together three subpatterns that match the unwanted cases as well as the wanted one.
Some simple examples:
URL that is already enclosed in <a ...> </a> tags:
<a\s[>]+>http://[\s]+</a>
URL within a tag:
<[>]+http://[>]+>
URL:
http://[\s]+
(modify them according to your needs)
EDITED: It may be useful to test each of them separately to make sure they match what you expect them to match.
2)
Combine them in an alternation. Make sure the unwanted cases go first, and enclose them in parenthesis:
pattern:
%(<a\s[>]+>http://[\s]+</a>)|(<[>]+http://[>]+>)|http://[\s]+%i
3)
Now you can make use of the e-modifier that allows to evaluate the replacement argument: if the complete match equals the first or second subpattern, replace it with itself, else add the link tag.
$text = "http://www.domain.com this was the first url, let's start a new line to celebrate this event.\n
However there is more to come <img scr=\"http://www.domain.net/pic.gif\">
Image path: http://www.domain.net/pic.gif
And here comes one enclosed in tags: <a href=\"http://www.domain.org\">http://www.domain.org</a>";
echo preg_replace('%(<a\\s[^>]+>http://[^\\s]+</a>)|(<[^>]+http://[^>]+>)|http://[^\\s]+%ie',
'"$0"=="$1" || "$0"=="$2" ? "$0" : "<a href=\"$0\">$0</a>"', $text);