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!
I solved my problem. The solution is to correct the second regex (URL parser) and add some conditions. New regex will look like this:
#(?<!src="|href=")(https?:\/\/([a-zA-Z0-9\-\.]+)\/?[a-zA-Z0-9?&=.:\#\/\-_~%+]*)#e'
And the whole code became this:
$line = preg_replace('#(?<!src="|href=")(https?:\/\/([a-zA-Z0-9\-\.]+)\/?[a-zA-Z0-9?&=.:\#\/\-_~%+]*)#e', '\'[<a href="$1" title="$1" target="_blank">$2</a>]\'',$line);
try this little helper function:
function parseCode($txt)
{
// these functions will clean the code first
$ret = strip_tags($txt);
// code replacements
$ret = preg_replace('#\[link\=(.+)\](.+)\[\/link\]#iUs', '<a href="$1">$2</a>', $ret);
$ret = preg_replace('#\[img\](.+)\[\/img\]#iUs', '<img src="$1" alt="Image" />', $ret);
// return parsed string
return $ret;
}
usage:
echo parseCode('[link=https://www.google.com]Click here to go to google[/link]');
echo "<br />";
echo parseCode('[img]https://www.google.co.uk/images/srpr/logo11w.png[/img]');