Skip to content

Instantly share code, notes, and snippets.

@theprogrammerin
Last active April 23, 2022 11:25
Show Gist options
  • Save theprogrammerin/9583354 to your computer and use it in GitHub Desktop.
Save theprogrammerin/9583354 to your computer and use it in GitHub Desktop.
Converts any url in string to a html http link tag
<?php
function linkify($string)
{
$reg_exUrl = "@(https://|http://|www)[^<>[:space:]]+[[:alnum:]/]@";
$links = array();
preg_match_all($reg_exUrl, $string, $urls);
foreach ($urls[0] as $url) {
$string = str_replace($url, "[[:link:".(count($links)).":]]" , $string);
$force_http = "";
if( strpos($url, "http://") === false && strpos($url, "https://") === false ){
$force_http = "http://";
}
array_push($links, "<a target='_blank' href='{$force_http}{$url}'>{$url}</a>");
}
for($i =0; $i< count($links); $i++){
$string = str_replace("[[:link:".($i).":]]", $links[$i], $string);
}
return $string;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment