Jeremy Karlsson Jeremy Karlsson - 3 years ago 115
PHP Question

Regex PHP - Auto-detect YouTube, image and "regular" links

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 code in Java for my WebIRC client but now I'm trying to make it in PHP and JavaScript.

I'm not familiar with PHP yet so I don't know that much about using regex there. I wonder if some kind soul could help me with this...

For the YouTube-thingy I tried this without success:

if (preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<[^&\n]+#", $message, $m)) {
$video_id = $m[1];
$message = preg_replace("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<[^&\n]+#","<iframe class='embedded-video' src='" . $video_id . "' allowfullscreen></iframe>",$message);

Answer Source

Here is a solution I came up with:

$str = 'This is an image:



$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 '<img src="'. $arr[0] . '" />';
    // youtube
    if(in_array($url['host'], array('', ''))
      && $url['path'] == '/watch'
      && isset($url['query']))
        parse_str($url['query'], $query);
        return sprintf('<iframe class="embedded-video" src="" allowfullscreen></iframe>', $query['v']);
    return sprintf('<a href="%1$s">%1$s</a>', $arr[0]);
}, $str);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download