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) insert the anchor tags for the link (showing the link itself as the link text) ?
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;
}
Edit: Added tilde to make urls work better https://regexr.com/5m16v
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With