开发者

How do I use preg_replace to make a correct URL

开发者 https://www.devze.com 2023-03-16 16:38 出处:网络
I\'m trying to find a pattern for preg_replace which will match incorrectly formed HTML links / URLs in a paragraph and replace them with correct links. I\'m really not sure how to start with it.

I'm trying to find a pattern for preg_replace which will match incorrectly formed HTML links / URLs in a paragraph and replace them with correct links. I'm really not sure how to start with it.

This is how I need the URL to be formed (http:// needs to be include开发者_如何学Pythond):

<a href="http://www.example.com" target="_blank">www.example.com</a>

Bad URLs may well come in the form of:

example.com
www.example.co.uk
<a href="example.com">example.com</a>
<a href=example.com>example.com</a>

Any help or advise would be greatly appreciated.

Thanks,

eb_dev


Ok found a solution that seems to work pretty well:

$msg = preg_replace(
                   "#(^|[\n ])([\w]+?://[^ \"\n\r\t<]*)#is",
                   "$1<a href=\"$2\" target=\"_blank\">$2</a>",
                   $msg
                   );

$msg = preg_replace(
                   "#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#is",
                   "$1<a href=\"http://$2\" target=\"_blank\">$2</a>",
                   $msg
                   ); 
0

精彩评论

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