Stripping and/or altering the content of a custom field (video URL)

Whipped up a nifty little parsing function for you:

function wpse44048_parse_video_link( $link ) {
    $url="some url"; // pass this in
    $parsed_url = parse_url( $url );

    $host = $parsed_url['host'];

    // check that the service exists, otherwise return false
    if( strpos( $host, 'youtube.com' ) !== false
     && strpos( $host, 'youtu.be' ) !== false
     && strpos( $host, 'vimeo.com' ) !== false ) {
         return false;
    }

    // set $service
    if( strpos( $host, 'youtube.com' ) !== false
     || strpos( $host, 'youtu.be' ) !== false ) {
        $service="youtube";
    }
    if( strpos( $host, 'vimeo.com' ) !== false ) {
        // handle vimeo
        $service="vimeo";
    }

    // set $video_id
    if( strpos( $host, 'youtube.com' ) !== false ) {
        // handle youtube regular url
        $vars = array();

        parse_str( $parsed_url['query'], $vars );

        $video_id = $vars['v'];
    }
    if( strpos( $host, 'youtu.be' ) !== false ) {
        // handle youtube shortened URL
        $video_id = $parsed_url['path'];
    }
    if( strpos( $host, 'vimeo.com' ) !== false ) {
        // handle vimeo
        $video_id = $parsed_url['path'];
    }

    return array(
        'service' => $service, // youtube or vimeo
        'id'      => $video_id // the id of the video
    );
}

No testing done on that, but I based it on this stackoverflow answer. The function is expansible, though you may want to rewrite it. I wrote it to use a centralized value for the services so youtube.com and youtu.be links wouldn’t return a different service if you changed them, but you could definitely do existence check, set $service, and set the $video_id all in one if, elseif, else group. General concept is there for you though.

tech