Created
May 18, 2017 16:27
-
-
Save AndyCouch/ff84d6195ac1c4f07c0b6cf4e29e4c8e to your computer and use it in GitHub Desktop.
PHP Auto-link Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function auto_link($text) { | |
$pattern = '/(((http[s]?:\/\/(.+(:.+)?@)?)|(www\.))[a-z0-9](([-a-z0-9]+\.)*\.[a-z]{2,})?\/?[a-z0-9.,_\/~#&=:;%+!?-]+)/is'; | |
$text = preg_replace($pattern, ' <a href="$1">$1</a>', $text); | |
// fix URLs without protocols | |
$text = preg_replace('/href="www/', 'href="http://www', $text); | |
return $text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was one of the most popular code snippets on my old blog and I still use it to this day, so I decided to port it over to this Gist. Let me know if you run into any issues where this doesn't match a valid URL or matches something that's not a valid URL.