SO Community!
I am new to regular expressions and I have a trouble with them.
I have a chat script with simple parser of user data.
There is an ability to embed an image with BBCode tag, like this: [img]http://example.com/image.png[/img]
.
I also want to do automatic link transformation to valid hyperlinks.
I have two processing REGEXes, and I don't know how to solve the conflict between them.
To process [img]
tag I use this and it executes first:
$line = preg_replace('/\[img\](https?:\/\/[a-zA-Z0-9%\-_?&=:+.\/]+)\[\/img\]/iU', '<a href="$1" target="_blank"><img class="incl_img" src="$1"></a>', $line, 5);
Then to process links I use this:
$line = preg_replace('#(https?:\/\/([a-zA-Z0-9-.]+)\/?[a-zA-Z0-9?&=.:\#\/\-_~%+]*)#e', '\'[<a href="$1" title="$1" target="_blank">$2</a>]\'',$line);
And when user posts an image the link processing regex breaks <img>
tag by inserting its <a href=...
instead of link. How to avoid it without using special [url]
tag or something else? How to separate [img]
tags from simple links? Any corrections of regexes and/or algorithms are welcome. Thanks in advance!