I have text that supports BBCode and I use a custom PHP function to do the replacing instead of using PECL package or anything. It's working great to turn:
[url=http://www.google.com]Google[/url]
to
<a href="http://www.google.com" target="_blank">Google</a>
I also have a custom BBCode tag that turns the tag into an iframe:
[customtag]abc[/customtag]
to
<iframe src="http://example.com/abc"></iframe>
But now I have a requirement to change urls that are just typed normally to turn them into links. So if you type:
http://www.google.com
it will turn it into:
<a href="http://www.google.com" target="_blank">Google</a>
I've used this regex to do this:
$string = preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $string);
But it's also matching what is in bbcode. If I include it after I parse the bbcode then it changes things in the anchor. Also happens for images and the iframe.
So how I can I change plain urls but ignore ones that are within a bbcode tag or already in a html tag?