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
);
精彩评论