0

Basically what I want is to have a html textarea field, where the user can write a comment. If the user writes a url, I want to highlight this url. Example bellow:

"Hi! This is a comment. This is a link to http://www.google.com and the comment continues."

I want my regular expression to match urls formatted as follows:

  1. http://google.com
  2. http://www.google.com
  3. www.google.com

I don't want to match urls formatted as follows

  1. google.com
  2. www.com

So far my regular expression looks like this:

/(http)?(s)?(:\/\/)?((w*\.)([a-zA-Z0-9])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])/

but the problem is that it cannot match http://google.com (1) of the list above.

I know that this topic may be marked as duplicate and I apology but I wasn't able to find exactly what I need anywhere. Any help is appreciated :)

  • 2
    A google search with `php extract url from text` returned a bunch of results. None of them helped you?: [**result 1**](http://stackoverflow.com/q/910912/4577762) - [**result 2**](http://stackoverflow.com/a/4390768/4577762) - [**result 3**](http://stackoverflow.com/q/1959062/4577762) ... – FirstOne Jun 28 '16 at 12:18
  • Thanks for the heads up Fred. I was just about to start coding. Now my mind will go elsewhere – Andreas Jun 28 '16 at 12:18
  • There are lots of question like this but just for your question add (w*\.)? instead of (w*\.) will work for you.. – Shekhar Khairnar Jun 28 '16 at 12:22
  • @FirstOne I have read this topics but the solutions there are not the think I am looking for. For example they match google.com and I don't want it to be matched. – whiplash911 Jun 28 '16 at 12:23
  • 4
    `(https?:\/\/(www\.)?|www\.)([\w-]+\.)+[\w-]+` https://www.regex101.com/r/hZ6yL0/2 – splash58 Jun 28 '16 at 12:26
  • @ShekharKhairnar I tried that before but if I make (w*\.)? (optional because of the ?) I will match urls like google.com which I don't want to. Thanks for the answer tho. – whiplash911 Jun 28 '16 at 12:28
  • @splash58 Thank you for the answer. It solves my problem! – whiplash911 Jun 28 '16 at 12:34
  • one more way will be : https://regex101.com/r/hU4vO7/6 – Shekhar Khairnar Jun 28 '16 at 12:36

0 Answers0