Php parse links/emails

前端 未结 4 1107
时光取名叫无心
时光取名叫无心 2020-12-06 08:11

I am wondering if there is a simple snippet which converts links of any kind:

http://www.cnn.com to http://www.cnn.com&l         


        
4条回答
  •  误落风尘
    2020-12-06 08:44

    I know is 5 years late, however I needed a similar solution and the best answer I got was from the user - erwan-dupeux-maire

    Answer

    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+)?)?)*)@', '$1', $str);
        // add "http://" if not set
        $str = preg_replace('/]*href\s*=\s*"((?!https?:\/\/)[^"]*)"[^>]*>/i', '', $str);
        return $str;
    }
    

提交回复
热议问题