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

前端 未结 2 1160
野性不改
野性不改 2020-12-05 21:20

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

相关标签:
2条回答
  • 2020-12-05 21:57

    You can use regexp to do this:

    $html_links = preg_replace('"\b(https?://\S+)"', '<a href="$1">$1</a>', $text);
    
    0 讨论(0)
  • 2020-12-05 21:58

    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;
    }
    
    0 讨论(0)
提交回复
热议问题