2

I run a forum and want to automatically replace any link to a YouTube video with a youtube video player. I can't really find anything like this on the ineternet, but I have seen it in Wordpress.

I'm running PHP.

This is what i'm talking about:

http://en.support.wordpress.com/videos/youtube/

David
  • 14,182
  • 34
  • 96
  • 150
  • Have you thought of using BBCode? – vascowhite Jul 08 '11 at 08:32
  • I don't want to use anything extra that the uesr has to do. Just past in the URL and my code will replace the URL with a video player. wordpress does it.. – David Jul 08 '11 at 09:32
  • I'm not 100% on how to do this, but I assume it's an easy task to create a regular expression that will find a youtube link and extract the video ID. You can then insert that ID into a template of the embed codes and replace the link with it. – Hubro Jul 08 '11 at 10:39
  • Yea, thats how I see it as well. I have found a number of regex commands but none of them seem to allow me to find a youtube address in a block of text, extract the video id and replace the entire link with a video player. If i can't find a way to do this, im going to have to go down a bbcode method – David Jul 08 '11 at 12:35

5 Answers5

2

There are many, many questions on SO about regexping Youtube video IDs - just do a Google or site search. I took the liberty to modify this answer by ridgerunner to do what you want, ie. replace a Youtube URL with the embed code. Have a look and edit the pattern or embed code if needed. For example, you might want to wrap the embedded video in a div.

<?php

// Replace Youtube URLs with embed code
function embedYoutube($text)
{
    $search = '~
        # Match non-linked youtube URL in the wild. (Rev:20130823)
        (?:https?://)?    # Optional scheme.
        (?:[0-9A-Z-]+\.)? # Optional subdomain.
        (?:               # Group host alternatives.
          youtu\.be/      # Either youtu.be,
        | youtube         # or youtube.com or
          (?:-nocookie)?  # youtube-nocookie.com
          \.com           # followed by
          \S*             # Allow anything up to VIDEO_ID,
          [^\w\s-]        # but char before ID is non-ID char.
        )                 # End host alternatives.
        ([\w-]{11})       # $1: VIDEO_ID is exactly 11 chars.
        (?=[^\w-]|$)      # Assert next char is non-ID or EOS.
        (?!               # Assert URL is not pre-linked.
          [?=&+%\w.-]*    # Allow URL (query) remainder.
          (?:             # Group pre-linked alternatives.
            [\'"][^<>]*>  # Either inside a start tag,
          | </a>          # or inside <a> element text contents.
          )               # End recognized pre-linked alts.
        )                 # End negative lookahead assertion.
        [?=&+%\w.-]*      # Consume any URL (query) remainder.
        ~ix';

    $replace = '<object width="425" height="344">
        <param name="movie" value="http://www.youtube.com/v/$1?fs=1"</param>
        <param name="allowFullScreen" value="true"></param>
        <param name="allowScriptAccess" value="always"></param>
        <embed src="http://www.youtube.com/v/$1?fs=1"
            type="application/x-shockwave-flash" allowscriptaccess="always" width="425" height="344">
        </embed>
        </object>';

    return preg_replace($search, $replace, $text);
}

$string = 'This is the forum post content with some Youtube links:'."\n".
    'http://www.youtube.com/watch?v=NLqAF9hrVbY'."\n".
    'http://www.youtube.com/v/u1zgFlCw8Aw?fs=1&hl=en_US';

echo embedYoutube($string);

?>
Community
  • 1
  • 1
Viktor
  • 3,256
  • 1
  • 27
  • 40
  • @MichalWrd Looks like a revision (not mine) of the answer broke the regex for some cases. Anyway, I edited the pattern with the latest code from ridgerunner's excellent answer. Should work better now. – Viktor Mar 13 '15 at 23:15
1

You don't need to generate embedable HTML by hands, Youtube supports oEmbed protocol: http://oembed.com/#section5

Karolis
  • 8,967
  • 26
  • 38
0

Here's my version of Viktor's modification

/**
 * Finds youtube videos links and makes them an embed.
 * search: http://www.youtube.com/watch?v=xg7aeOx2VKw
 * search: http://www.youtube.com/embed/vx2u5uUu3DE
 * search: http://youtu.be/xg7aeOx2VKw
 * replace: <iframe width="560" height="315" src="http://www.youtube.com/embed/xg7aeOx2VKw" frameborder="0" allowfullscreen></iframe>
 *
 * @param string
 * @return string
 * @see http://stackoverflow.com/questions/6621809/replace-youtube-link-with-video-player
 * @see http://stackoverflow.com/questions/5830387/how-to-find-all-youtube-video-ids-in-a-string-using-a-regex
 */
function generateVideoEmbeds($text) {
    // No youtube? Not worth processing the text.
    if ((stripos($text, 'youtube.') === false) && (stripos($text, 'youtu.be') === false)) {
        return $text;
    }

    $search = '@          # Match any youtube URL in the wild.
        [^"\'](?:https?://)?  # Optional scheme. Either http or https; We want the http thing NOT to be prefixed by a quote -> not embeded yet.
        (?:www\.)?        # Optional www subdomain
        (?:               # Group host alternatives
          youtu\.be/      # Either youtu.be,
        | youtube\.com    # or youtube.com
          (?:             # Group path alternatives
            /embed/       # Either /embed/
          | /v/           # or /v/
          | /watch\?v=    # or /watch\?v=
          )               # End path alternatives.
        )                 # End host alternatives.
        ([\w\-]{8,25})    # $1 Allow 8-25 for YouTube id (just in case).
        (?:               # Group unwanted &feature extension
            [&\w-=%]*     # Either &feature=related or any other key/value pairs
        )
        \b                # Anchor end to word boundary.
        @xsi';

    $replace = '<iframe width="560" height="315" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
    $text = preg_replace($search, $replace, $text);

    return $text;
}
Svetoslav Marinov
  • 1,390
  • 12
  • 11
0

hello i need same code but my content got html + youtube url

so i update reg pattern

private function generateVideoEmbeds($text)
{
    // No youtube? Not worth processing the text.
    if ((stripos($text, 'youtube.') === false) && (stripos($text, 'youtu.be') === false))
    {
        return $text;
    }
    $replace = '<iframe width="560" height="315" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
    $text = preg_replace("/http:\/\/(www.)?(youtube.com|youtube.be)\/watch\?v=[\w]{8,25}[^< ]/si", $replace, $text);

    return $text;
}
Bdwey
  • 1,510
  • 1
  • 14
  • 16
0

You can try a tiny class for generating player's code - http://github.com/chernikovalexey/Livar. I've found it interesting ;)

Yaffle
  • 1