开发者

find all urls (links) in text with php

开发者 https://www.devze.com 2023-03-07 16:09 出处:网络
I have this code regex, which should transform all kind of diffrent urls into links in some text. The preg_replace code is:

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开发者_StackOverflow社区 :)

Thanks, best regards,


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!


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消