0

I have found alot of functions that answers my question in the top, but most of theese functions have problems. The best what I have so far found is this one

//Replace links with http://
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" class=\"chatlink\" target=\"_blank\" rel=\"nofollow\">\\2</a>", $ret);

//Replace links without http://
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" class=\"chatlink\" target=\"_blank\" rel=\"nofollow\">\\2</a>", $ret);

The problem is, this doesn't replace the url, if it is in the middle of the text. For example, it does not replace text in string something like this:

"Small text http://www.google.com , and some more text." It works fine if the link is not in the the middle of the text, but in new line.

And secondly I need to make sure, if in string already is html href link, that it doesn't replace the url again.

<a href="http://google.com">http://google.com</a>

<a href="<a href="http://google.com">http://google.com</a>"></a>

That would be it. Would be amazing if someone could help me, Im just not too good with preg_replace function.

  • 1
    Check this post http://stackoverflow.com/questions/4217406/php-add-link-to-a-url-in-a-string – Divyesh Savaliya Jul 20 '16 at 11:28
  • Make yourself more clear by just putting input strings(all possible), what code you have applied on them and what your expected outcome for each input. – Alive to die - Anant Jul 20 '16 at 11:33
  • I can't understand exactly what the problem is. Because what you've just described is working fine on that regex. I ran your regex and it replaced the link in that text. And also, it didn't replaced the url again. – Dianna Jul 20 '16 at 11:37
  • 1
    Thanks everyone for help, there was   before link, thats why it didn't work. Sorry for my mistake. – Sandis Andrianovs Jul 20 '16 at 11:57

0 Answers0