0

I've the following script which hyperlinks any links posted on my site:

    $text = trim($text);
    while ($text != stripslashes($text)) { $text = stripslashes($text); }    
    $text = strip_tags($text,"<b><i><u>");
    $text = preg_replace("/(?<!http:\/\/)www\./","http://www.",$text);
    $text = preg_replace( "/((http|ftp)+(s)?:\/\/[^<>\s]+)/i", "<a href=\"\\0\" target=\"_new\">\\0</a>",$text);

However, for some reason if I add a https://www.test.com link it ends up displaying like this - https://http://www.test.com - what am I doing wrong? How can I make it work with https links as well? It works fine with http links. Thank you! :-)

EdzJohnson
  • 1,137
  • 2
  • 8
  • 15
  • possible duplicate of [Need a good regex to convert URLs to links but leave existing links alone](http://stackoverflow.com/questions/287144/need-a-good-regex-to-convert-urls-to-links-but-leave-existing-links-alone) – hek2mgl Jun 04 '13 at 15:26

1 Answers1

1

The lookbehind that you have here, (?<!http:\/\/)www\. is only matching http://, but your test input (that's failing) is https://.

You can add a second lookbehind chained with the current one to specify the alternative https:// version too:

(?<!http:\/\/)(?<!https:\/\/)www\.

This would make your full line look like:

$text = preg_replace("/(?<!http:\/\/)(?<!https:\/\/)www\./","http://www.",$text);

The last I checked, PHP does not support variable-length lookbehinds, so things that may be familiar such as http[s]?:// wouldn't work here - hence the second pattern.

newfurniturey
  • 37,556
  • 9
  • 94
  • 102