Заменить ссылку YouTube на видео плеер - PullRequest
2 голосов
/ 08 июля 2011

Я запускаю форум и хочу автоматически заменить любую ссылку на видео YouTube на видеоплеер YouTube.Я не могу найти ничего подобного в интернете, но я видел это в Wordpress.

Я использую PHP.

Это то, о чем я говорю:

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

Ответы [ 5 ]

2 голосов
/ 11 июля 2011

В SO много вопросов по поводу регулярного определения идентификаторов видео на Youtube - просто выполните поиск в Google или на сайте. Я позволил себе изменить этот ответ от ridgerunner , чтобы сделать то, что вы хотите, т.е. заменить URL-адрес Youtube на код для встраивания. Посмотрите и отредактируйте шаблон или вставьте код, если это необходимо. Например, вы можете обернуть встроенное видео в 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);

?>
1 голос
/ 11 июля 2011

Вам не нужно создавать встраиваемый HTML вручную, Youtube поддерживает протокол oEmbed: http://oembed.com/#section5

0 голосов
/ 04 ноября 2013

привет мне нужен тот же код, но мой контент получил HTML + URL-адрес YouTube

, поэтому я обновляю рег шаблон

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;
}
0 голосов
/ 07 июня 2013

Вот моя версия модификации Виктора

/**
 * 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 /5034626/zamenit-ssylku-youtube-na-video-pleer
 * @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;
}
0 голосов
/ 30 июля 2011

Вы можете попробовать маленький класс для генерации кода игрока - http://github.com/chernikovalexey/Livar. Я нашел это интересным;)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...