Php youtube to iframe

Php iframe php youtube url code example

When considering the compexity/diversity of youtube urls, you may want to reference this list of examples that I pulled from StackOverflow pages and the internet. I will admit that this set of pattern could be refined further to be more condensed (fewere total patterns) and that the youtube validation patterns could be more strict, but I honestly don’t have time to go down those rabbit holes.

Specifically convert only YouTube urls to iframe tags while converting BBCode urls to html elements

Launching from your previous question, I’ve developed and tested a complete battery of regular expressions to get you on your way. I will admit that this set of pattern could be refined further to be more condensed (fewere total patterns) and that the youtube validation patterns could be more strict, but I honestly don’t have time to go down those rabbit holes.

Читайте также:  Mod fcgid apache php

When considering the compexity/diversity of youtube urls, you may want to reference this list of examples that I pulled from StackOverflow pages and the internet. https://regex101.com/r/zinjze/1

$bbcode = [/code][/li] [/ul] BBCODE; $search = array ( '~\[b](.*?)\[/b]~is', '~\[i](.*?)\[/i]~is', '~\[u](.*?)\[/u]~is', '~\[ul](.*?)\[/ul]~is', '~\[li](.*?)\[/li]~is', '~\[user=(.*?)](.*?)\[/user]~i', '~\[url=https?.*?(?:[/?&](?:e|vi?|ci)(?:[/=]|%3D)|youtu\.be/|embed/|/user/[^/]+#p/(?:[^/]+/)+)([\w-])].*?\[/url]~i', '~\[url]https?.*?(?:[/?&](?:e|vi?|ci)(?:[/=]|%3D)|youtu\.be/|embed/|/user/[^/]+#p/(?:[^/]+/)+)([\w-]).*?\[/url]~i', '~\[url=((?:ht|f)tps?://[a-z\d.-]+\.[a-z]/\S*?)](.*?)\[/url]~i', '~\[url]((?:ht|f)tps?://[a-z\d.-]+\.[a-z]/\S*?)\[/url]~i', '~\[img=(.*?)].*?\[/img]~i', '~\[quote](.*?)\[/quote]~is', '~\[code](.*?)\[/code]~is', '~(?:|)(*SKIP)(*FAIL)|(?:\bhttps?.*?(?:[/?&](?:e|vi?|ci)(?:[/=]|%3D)|youtu\.be/|embed/|/user/[^/]+#p/(?:[^/]+/)+)([\w-]))\S*~i', '~(?:|)(*SKIP)(*FAIL)|\bhttps?://.+?(?=\s|$)~im' ); $replace = array ( '$1', '$1', '$1', '
    $1
', ' $1', '$2', '', '', '$2', '$1', ' ', '$1', '$1', '', '$0' ); echo preg_replace($search, $replace, $bbcode);

Unrendered Output: ( you can copy-paste my snippet in http://phptester.net/ if you want to see the rendered output )

Want a list? 
  • Here is a video:
  • This is a tagged video:
  • This is a tagged & attributed video:
  • Look at this:https://www.example.com/example?ohyeah=sure#okay this is a raw link
  • No attibute bbcode url: http://example.com/x1
  • A url with link and link text: x2
  • Image with \"ignorable" text:
  • Image:
  • "I could either watch it happen or be a part of it." - Elon Musk
  • mickmackusa
  • Code: while ($noSuccess)

I managed to fix my problem by swapping my code around so it converts YouTube links first then the other URLs second and changing it a little. New code:

Php - Specifically convert only YouTube urls to iframe, I'm trying to convert youtube video links into iframes to embed them onto my website but I'm having a problem as I am already converting urls to anchor tags and it's conflicting with the youtube ur

How To Embed YouTube Videos with iframe Tag in

With the HTML iframe Tag, you can embed a YouTube Video or another website into your HTML Document and Website.The …

HTML iframe Example and Tutorial

http://www.LittleWebHut.comThis video demonstrates how to use the HTML / XHTML iframe tag. It will cover the basic usage for the iframe tag and demonstrate t

Accessing an iframe document (contentWindow)

In this video we take a look at the contentWindow and contentDocument properties of an embedded iframe - it allows access to the underlying "window" and "doc

PHP Coding making different Iframe codes appear

You could simplify this easily. Try adding the sites to an array like this:

$sites = array( 'site1.com', 'site2.com', 'site3.com', 'site4.com', 'site5.com', 'site6.com', 'site7.com' );

Now you can use features like array_rand() to pick a random entry from the site to show in your :

  

Or you could even use rand() like this:

 

That avoids the hassles of large if else or switch case statements.

Url - getting youtube video id the PHP, I am currently writing a webapp in which some pages are heavily reliant on being able to pull the correct youtube video in - and play it. The youtube URLS are supplied by the users and for this reason will generally come in with variants one of them may look like this:

PHP strip iframe except YouTube with regular expression

Since googling up php strip tags except youtube linked me here, I think I should give a go at suggesting an alternative answer.

Maybe you'd like to use a library like HTML Purifier? Malte already suggested a way of doing this in https://stackoverflow.com/a/12784081/2716927.

Untested code but should work pretty much like this:

require_once 'htmlpurifier/library/HTMLPurifier.auto.php'; $config = HTMLPurifier_Config::createDefault(); $config->set('HTML.Trusted', true); $config->set('HTML.SafeIframe', true); $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%'); //allow YouTube and Vimeo $purifier = new HTMLPurifier($config); $text = $purifier->purify($document); 

Php - Get youtube id for all url types, Your right it does work but in order to make it embeded it needs to be places inbetween [youtube] [/youtube] and the youtu.be url ends up trimming the code box to "[youtube]youtube]" but yet with the other urls it works perfectly. Never noticed that until now. –

Источник

Php iframe php youtube url code example

When considering the compexity/diversity of youtube urls, you may want to reference this list of examples that I pulled from StackOverflow pages and the internet. I will admit that this set of pattern could be refined further to be more condensed (fewere total patterns) and that the youtube validation patterns could be more strict, but I honestly don't have time to go down those rabbit holes.

Specifically convert only YouTube urls to iframe tags while converting BBCode urls to html elements

Launching from your previous question, I've developed and tested a complete battery of regular expressions to get you on your way. I will admit that this set of pattern could be refined further to be more condensed (fewere total patterns) and that the youtube validation patterns could be more strict, but I honestly don't have time to go down those rabbit holes.

When considering the compexity/diversity of youtube urls, you may want to reference this list of examples that I pulled from StackOverflow pages and the internet. https://regex101.com/r/zinjze/1

$bbcode = [/code][/li] [/ul] BBCODE; $search = array ( '~\[b](.*?)\[/b]~is', '~\[i](.*?)\[/i]~is', '~\[u](.*?)\[/u]~is', '~\[ul](.*?)\[/ul]~is', '~\[li](.*?)\[/li]~is', '~\[user=(.*?)](.*?)\[/user]~i', '~\[url=https?.*?(?:[/?&](?:e|vi?|ci)(?:[/=]|%3D)|youtu\.be/|embed/|/user/[^/]+#p/(?:[^/]+/)+)([\w-])].*?\[/url]~i', '~\[url]https?.*?(?:[/?&](?:e|vi?|ci)(?:[/=]|%3D)|youtu\.be/|embed/|/user/[^/]+#p/(?:[^/]+/)+)([\w-]).*?\[/url]~i', '~\[url=((?:ht|f)tps?://[a-z\d.-]+\.[a-z]/\S*?)](.*?)\[/url]~i', '~\[url]((?:ht|f)tps?://[a-z\d.-]+\.[a-z]/\S*?)\[/url]~i', '~\[img=(.*?)].*?\[/img]~i', '~\[quote](.*?)\[/quote]~is', '~\[code](.*?)\[/code]~is', '~(?:|)(*SKIP)(*FAIL)|(?:\bhttps?.*?(?:[/?&](?:e|vi?|ci)(?:[/=]|%3D)|youtu\.be/|embed/|/user/[^/]+#p/(?:[^/]+/)+)([\w-]))\S*~i', '~(?:|)(*SKIP)(*FAIL)|\bhttps?://.+?(?=\s|$)~im' ); $replace = array ( '$1', '$1', '$1', '
    $1
', ' $1', '$2', '', '', '$2', '$1', ' ', '$1', '$1', '', '$0' ); echo preg_replace($search, $replace, $bbcode);

Unrendered Output: ( you can copy-paste my snippet in http://phptester.net/ if you want to see the rendered output )

Want a list? 
  • Here is a video:
  • This is a tagged video:
  • This is a tagged & attributed video:
  • Look at this:https://www.example.com/example?ohyeah=sure#okay this is a raw link
  • No attibute bbcode url: http://example.com/x1
  • A url with link and link text: x2
  • Image with \"ignorable" text:
  • Image:
  • "I could either watch it happen or be a part of it." - Elon Musk
  • mickmackusa
  • Code: while ($noSuccess)

I managed to fix my problem by swapping my code around so it converts YouTube links first then the other URLs second and changing it a little. New code:

Php - Specifically convert only YouTube urls to iframe, I'm trying to convert youtube video links into iframes to embed them onto my website but I'm having a problem as I am already converting urls to anchor tags and it's conflicting with the youtube ur

How To Embed YouTube Videos with iframe Tag in

With the HTML iframe Tag, you can embed a YouTube Video or another website into your HTML Document and Website.The …

HTML iframe Example and Tutorial

http://www.LittleWebHut.comThis video demonstrates how to use the HTML / XHTML iframe tag. It will cover the basic usage for the iframe tag and demonstrate t

Accessing an iframe document (contentWindow)

In this video we take a look at the contentWindow and contentDocument properties of an embedded iframe - it allows access to the underlying "window" and "doc

PHP Coding making different Iframe codes appear

You could simplify this easily. Try adding the sites to an array like this:

$sites = array( 'site1.com', 'site2.com', 'site3.com', 'site4.com', 'site5.com', 'site6.com', 'site7.com' );

Now you can use features like array_rand() to pick a random entry from the site to show in your :

  

Or you could even use rand() like this:

 

That avoids the hassles of large if else or switch case statements.

Url - getting youtube video id the PHP, I am currently writing a webapp in which some pages are heavily reliant on being able to pull the correct youtube video in - and play it. The youtube URLS are supplied by the users and for this reason will generally come in with variants one of them may look like this:

PHP strip iframe except YouTube with regular expression

Since googling up php strip tags except youtube linked me here, I think I should give a go at suggesting an alternative answer.

Maybe you'd like to use a library like HTML Purifier? Malte already suggested a way of doing this in https://stackoverflow.com/a/12784081/2716927.

Untested code but should work pretty much like this:

require_once 'htmlpurifier/library/HTMLPurifier.auto.php'; $config = HTMLPurifier_Config::createDefault(); $config->set('HTML.Trusted', true); $config->set('HTML.SafeIframe', true); $config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%'); //allow YouTube and Vimeo $purifier = new HTMLPurifier($config); $text = $purifier->purify($document); 

Php - Get youtube id for all url types, Your right it does work but in order to make it embeded it needs to be places inbetween [youtube] [/youtube] and the youtu.be url ends up trimming the code box to "[youtube]youtube]" but yet with the other urls it works perfectly. Never noticed that until now. –

Источник

Вставка видео из youtube по ссылке (PHP)

vstavka-video-s-youtube

Одним из популярных видео-проектов в интернете на сегодняшний день является сайт youtube.com. В виду популярности проекта ссылки на видео могут быть использованы довольно часто и на других сайтах. К примеру, впролне обуздана возможность вставки видео с ютуба на других сайтах, с использованием iframe.

Рассмотрим пример, как можно автоматизировать этот процесс. Первоначально у нас будет ссылка на какое-либо видео. Мы же будет вставлять это видео на страницу, с использованием этой ссылки.

Суть в том, что нам нужно извлечь значение параметра «v» из ссылки, это и есть идентификатор видео. После этого остается лишь правильно вставить фрейм с ссылкой сформированной с помощью этого параметра.

Приступаем, для наглядности сделаем форму для вставки ссылки на видео:

if (isset($_POST['url']) && filter_var($_POST['url'],FILTER_VALIDATE_URL,FILTER_FLAG_PATH_REQUIRED)) < $videoID = getYoutubeVideoID($_POST['url']); >else

Функция getYoutubeVideoID() извлекает идентификатор видео на ютюбе, и помещается в переменную $videoID.

Вставка iframe:

  ?>

Код функции getYoutubeVideoID():

// получение ID видео из URL function getYoutubeVideoID($url) < // допустимые доменые имена в ссылке $names = array('www.youtube.com','youtube.com'); // разбор адреса $up = parse_url($url); // проверка параметров if (isset($up['host']) && in_array($up['host'],$names) && isset($up['query']) && strpos($up['query'],'v=') !== false)< // достаем параметр ID $lp = explode('v=',$url); // отсекаем лишние параметры $rp = explode('&',$lp[1]); // возвращаем строку, либо false return (!empty ($rp[0]) ? $rp[0] : false); >return false; >

Ну и как полагается в конце: исходник и пример работы.

UPD: Добавляю альтернативный вариант реализации без использования PHP
В данном примере всё реализовано без использования PHP. В этом случае ссылка добавляется в элемент iframe посредством использования кода на JavaScript и библиотеки JQuery.
Не забудьте предварительно подключить библиотеку JQuery перед использованием кода примера.

Форма для ввода ссылки, а так же сам элемент iframe:

Обработчик события нажатия кнопки на форме:

// реакция на событие клика по кнопке на форме $('input[name="getlink"]').on("click",function() < // проверяем наличие записи в поле ввода if ($("#ylink").val() != '')< // получаем строку из поля ввода, разбиваем её на части (от знака =) var url_obj = $("#ylink").val().split('='); // проверяем наличие нужной записи if (typeof url_obj == 'object' && '1' in url_obj)< // формируем ссылку для iframe var link = 'http://www.youtube.com/embed/'+url_obj[1]+'?autoplay=0'; // добавляем ссылку в атрибут src элемента iframe $("#video-frame").attr("src", link); >else < alert('Не удалось получить параметр ссылки'); >> >);

Источник

Оцените статью