1

I have this code regex, which should transform all kind of diffrent urls into links in some text.

The preg_replace code is:

$regex = '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@';
$text = preg_replace($regex, '<a href="$1">$1</a>', $item);

now it works for almost all URLs you can imagine, but the problems i have are commas, and special characters in URLs...

The problem is making me:

http://www.sdfsdfsdf.sd/si/391,1000,1/more.html

http://sdfsddsdf-sdfsdfds.sr/component/option,com_contact/Itemid,3/lang,si/

Funny here at stackoverflow those two are OK :)

Thanks, best regards,

Community
  • 1
  • 1
Luka
  • 107
  • 1
  • 7

3 Answers3

6

You have to edit your regex a bit. This will do the job:

$regex = '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.\,]*(\?\S+)?)?)*)@';

As you can see, there's a comma added here [-\w/_\.\,] and nothing more.

Enjoy!

Bogdan Constantinescu
  • 5,296
  • 4
  • 39
  • 50
  • the problem with comma is that if you then have "http://www.avto.si/, http://www.avtooglasnik.com/, http://www.avtooglasi.com/," these three would be matched with comma, what is wrong ofcourse :) any idea? – Luka May 19 '11 at 22:15
  • @Luka: no, only the last would be matched with the comma inside, the others would be matched only as domains with the comma not taken into consideration. The comma has to be after a slash (`/`) to be matched as part of a url based on the regex above – Bogdan Constantinescu May 19 '11 at 22:23
  • but you never have url that starts with comma, so that should be invalid, can you make it like that? thx for answer anyway, best :) – Luka May 19 '11 at 23:21
  • ok so there are several issues with this solution.. `1. it doesn't append http:// or www before url , if url inputs google.com..` `2. if someone enters "true...it" or "true..it" , it converts it to a link..` – abhij89 Jun 15 '15 at 06:38
2

Try using the following function:

function replaceURLWithHTMLLinks(text) {
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(exp,"<a href='$1'>$1</a>"); 
}

Found it here: How to replace plain URLs with links?

Community
  • 1
  • 1
Jeroen
  • 13,056
  • 4
  • 42
  • 63
  • This doesn't match all possible URL, as you limit it to four schemata (http, https, ftp and file). – Hyperboreus May 19 '11 at 22:11
  • yes, this doesnt match alot of URLs, like sdkfskd.cs or www.google.cz etc, etc,... Thanks anyway. – Luka May 19 '11 at 22:16
-1

You can use this lib https://github.com/mxkh/url-finder for simple finding URLs in HTML page or in text. Iinstall with composer composer require mxkh/url-finder

Also this lib has a support for finding video links from popular video services sach as Youtube, Vimeo.

I hope this is helpful to someone.

Max H.
  • 1
  • 1
  • 1