find all urls (links) in text with php

2020-03-30 15:34发布

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,

3条回答
走好不送
2楼-- · 2020-03-30 16:14

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.

查看更多
劳资没心,怎么记你
3楼-- · 2020-03-30 16:18

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?

查看更多
混吃等死
4楼-- · 2020-03-30 16:20

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!

查看更多
登录 后发表回答