Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace any url's within a string of text, to clickable links with php

Tags:

regex

php

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) ?

like image 634
mrpatg Avatar asked Nov 25 '09 18:11

mrpatg


2 Answers

You can use regexp to do this:

$html_links = preg_replace('"\b(https?://\S+)"', '<a href="$1">$1</a>', $text);
like image 144
Ivan Nevostruev Avatar answered Nov 07 '22 06:11

Ivan Nevostruev


I write this function. It replaces all the links in a string. Links can be in the following formats :

  • www.example.com
  • http://example.com
  • https://example.com
  • example.fr

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

like image 20
Erwan Avatar answered Nov 07 '22 07:11

Erwan