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 :)

8
  • 2
    A google search with php extract url from text returned a bunch of results. None of them helped you?: result 1 - result 2 - result 3 ... Commented Jun 28, 2016 at 12:18
  • Thanks for the heads up Fred. I was just about to start coding. Now my mind will go elsewhere Commented Jun 28, 2016 at 12:18
  • There are lots of question like this but just for your question add (w*\.)? instead of (w*\.) will work for you.. Commented Jun 28, 2016 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. Commented Jun 28, 2016 at 12:23
  • 4
    (https?:\/\/(www\.)?|www\.)([\w-]+\.)+[\w-]+ regex101.com/r/hZ6yL0/2 Commented Jun 28, 2016 at 12:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.