Say i have a string of text such as
$text = \"Hello world, be sure to visit http://whatever.com today\";
how can i (probably using regex) i
You can use regexp to do this:
$html_links = preg_replace('"\b(https?://\S+)"', '<a href="$1">$1</a>', $text);
I write this function. It replaces all the links in a string. Links can be in the following formats :
The second argument is the target for the link ('_blank', '_top'... can be set to false). Hope it helps...
public static function makeLinks($str, $target='_blank')
{
if ($target)
{
$target = ' target="'.$target.'"';
}
else
{
$target = '';
}
// find and replace link
$str = preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1" '.$target.'>$1</a>', $str);
// add "http://" if not set
$str = preg_replace('/<a\s[^>]*href\s*=\s*"((?!https?:\/\/)[^"]*)"[^>]*>/i', '<a href="http://$1" '.$target.'>', $str);
return $str;
}