Created
January 18, 2018 17:25
-
-
Save zainaali/8d56e88affbcb1a51bb0fb182f868cb5 to your computer and use it in GitHub Desktop.
find links in a string and replace them with actual html link tags
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
<?php | |
$urls = "yahoo.com Regexes are not a magic wand that you wave at every problem that involves strings. Plus," | |
. " validation of URLs is a solved problem that you do not need to solve yourself. " | |
. "google.com You use existing http://maxworth.ca/wp-admin/customize.php?return=%2Fwp-admin%2Fupdate-core.php&autofocus%5Bcontrol%5D=background_image code google.com that has bing.com already " | |
. "been https://google.com written, tested and debugged"; | |
function makeUrls($urls) { | |
$url_list = preg_split('/[\s]+/', $urls); | |
$pattern = '/(?:https?:\/\/)?(?:[a-zA-Z0-9.-]+?\.(?:[a-zA-Z])|\d+\.\d+\.\d+\.\d+)/'; | |
$newString = ''; | |
foreach ($url_list as $key => $value) { | |
if (preg_match($pattern, $value)) { | |
$url = $value; | |
if(substr($url, 0, 4) != 'http') | |
$url = "http://".$url; | |
$newString .= "<a target='_blank' href=" . $url . ">{$value}</a> "; | |
} else { | |
$newString .= $value . ' '; | |
} | |
} | |
return $newString; | |
} | |
echo makeUrls($urls); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment