Regex PHP - Auto-detect YouTube, image and “regular” links

前端 未结 3 500
情话喂你
情话喂你 2020-12-17 04:47

I want to make it so that in my chat-application, links to websites can be clickable and links to YouTube and images automatically gets embedded.

I\'ve made this cod

3条回答
  •  温柔的废话
    2020-12-17 05:39

    Here is a solution I came up with:

    $str = 'This is an image: google.ca/images/srpr/logo3w.png
    
    YouTube: http://www.youtube.com/watch?v=V2b8ilapFrI&feature=related
    
    Stackoverflow:  http://stackoverflow.com/';
    
    $str = preg_replace_callback('#(?:https?://\S+)|(?:www.\S+)|(?:\S+\.\S+)#', function($arr)
    {
        if(strpos($arr[0], 'http://') !== 0)
        {
            $arr[0] = 'http://' . $arr[0];
        }
        $url = parse_url($arr[0]);
    
        // images
        if(preg_match('#\.(png|jpg|gif)$#', $url['path']))
        {
            return '';
        }
        // youtube
        if(in_array($url['host'], array('www.youtube.com', 'youtube.com'))
          && $url['path'] == '/watch'
          && isset($url['query']))
        {
            parse_str($url['query'], $query);
            return sprintf('', $query['v']);
        }
        //links
        return sprintf('%1$s', $arr[0]);
    }, $str);
    

    Let me know if you need me to clarify anything for you.

提交回复
热议问题