I'm using preg_replace to automatically encode URLs, mailtos and such in text blocks read back from a database. It works great when the links in the database are simple - i.e. "send email to bob@domain.com" or "visit us at www.domain.com" - my function wraps the necessary <a href=""> stuff around the links.
The problem is when the links are more complex - when there's text like "send email to <a href="mailto:bob@domain.com">Bunner Bob</a>" . In this case I don't want the preg_replace function to do its thing - the link is already encoded. I know there's a simple way to do this, a way of saying (for each of the three conditions - mail, http/www and ftp) "when this ISN'T preceded by '<a href='", but the proper syntax escapes me.
My function looks like this:
function HTMLEncode($text) {
return preg_replace(array("/(([\w\.]+))(@)([\w\.]+)\b/i", "/((ftp(7?):\/\/)|(ftp\.))([\w\.\/\&\=\?\-]+)/", "/((http(s?):\/\/)|(www\.))([\w\.\/\&\=\?\%\#\-]+)/"),
array("<a href=\"mailto:$0\">$0</a>", "<a href=\"ftp$3://$4$5\" target=\"_blank\">ftp$3://$4$5</a>", "<a href=\"http$3://$4$5\" target=\"_blank\">http$3://$4$5</a>"), $text);
}
Can someone help me out?
Thanks!
- Bob
Note: this is a repost of a question I asked previously, rewritten for simplicity.