Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Replace YouTube Links in Text with Embed Code

This article is one that resided on Internoetics. We've migrated it here (in part) for the sake of preservation. Only minor modifications were made to the code.

■ ■ ■

The code on this page was originally applied to our old (and soon-to-be reborn) Usenet website. The text within each Usenet post is rather static in nature so we applied as much formatting as we could think of to bring those newsgroup articles to life. Part of this strategy included identifying YouTube video links and making that video available from within content of the post.

Consider this text:

As part of an aviation media venture, we recorded various Boeing 777 test footage in different situations. We took several hours of video in a Boeing 777 simulator to determine the most effective means of communicating various principles. Take, for example, this video that illustrates part of the pre-takeoff safety brief. After purchasing a few GoPro cameras, our initial camera tests were conducted simply by attaching the unit to the quarter windows of an aircraft. Here is an approach into LAX , while this is an approach into Sydney (http://youtu.be/T4eZ24ZjRgE). The next stage of our 777 Video Series is due to commence early September.

Note: None of the referenced videos above are live to public.

Find YouTube Videos and Create an Array

By parsing the text body you may extract each YouTube video reference (and create an array of all the discovered YouTube videos).

1
preg_match_all('/https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[?=&+%\w-]*/i', $content, $output);

The $output array will look like this:

1
<?php 
2
 => Array
3
     (
4
        [0] => http://www.youtube.com/watch?v=B1a6VddQgxA
5
        [1] => http://www.youtube.com/watch?v=lxo2SlrxUYg
6
        [2] => http://youtu.be/T4eZ24ZjRgE
7
        [3] => http://www.youtube.com/watch?v=B1a6VddQgxA
8
     )
9
 
10
  [1] => Array
11
     (
12
        [0] => B1a6VddQgxA
13
        [1] => lxo2SlrxUYg
14
        [2] => T4eZ24ZjRgE
15
        [3] => B1a6VddQgxA
16
     )
17
 
18
)

To remove duplicate array values we use array_unique($output);. We can now do whatever we want with the returned video values. The most common application might be rendering each video with embed code or displaying video details with a thumbnail.

Render YouTube Videos from Array

If all I wanted to do was render the embed code of each video we found under the text body, I could use the following:

1
<?php 
2
/*
3
 Replace YouTube Links in Text with Embed Code
4
 http://www.beliefmedia.com/code/php-snippets/find-replace-youtube-links
5
*/
6
 
7
function beliefmedia_youtube_links($content, $width = '500') {
8
 
9
  /* Get YouTube links */
10
  preg_match_all('/https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[?=&+%\w-]*/i', $content, $output);
11
  if (empty($output)) return false;
12
 
13
  /* Remove duplicates */
14
  $output = $output['1'];
15
  $content = array_unique($output);
16
 
17
  /* Video height */
18
  $height = round($width / 1.777);
19
 
20
  foreach ($content AS $video_id) {
21
    $return .= '<div style="margin: 0 auto; padding-top: 20px;"><iframe loading="lazy" width="' . $width . '" height="' . $height . '" src="https://www.youtube.com/embed/' . $video_id . '" frameborder="0" allowfullscreen></iframe></div>';
22
  }
23
 
24
 return $return;
25
}
26
 
27
/* Usage */
28
echo beliefmedia_youtube_links($content);

The above code will embed each video on the page as follows:

YouTube Videos Embedded into Page

YouTube Videos Embedded into Page

While the above shows only a static image, it's an actual video that's rendered in a tower (not unlike the WP shortcode provided here).

We have a post forthcoming on our blog that deals with retrieving video details from YouTube's API. Using the API we can provide additional video details such as the title, description, running time, and interactions.

Return Video Thumbnails

A modified version of the function will return all discovered videos in a row of thumbnails. The function below is isn't a solution; it's just illustrative of how the idea might be implemented. We've used the second beliefmedia_youtube_thumbnail() function as provided on this page. The example function is as follows:

1
<?php 
2
/*
3
 Replace YouTube Links in Text with Embed Code
4
 http://www.beliefmedia.com/code/php-snippets/find-replace-youtube-links
5
*/
6
 
7
function beliefmedia_youtube_thumb_links($content, $size = '5') {
8
 
9
  /* Get YouTube links */
10
  preg_match_all('/https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[?=&+%\w-]*/i', $content, $output);
11
  if (empty($output)) return false;
12
 
13
  /* Remove duplicates */
14
  $output = $output['1'];
15
  $content = array_unique($output);
16
 
17
  foreach ($content AS $video_id) {
18
    $thumb = beliefmedia_youtube_thumbnail($video_id, '5');
19
    $return .= '<a href="http://youtu.be/' . $video_id . '" target="_blank" rel="noopener noreferrer"><img loading="lazy" src="' . $thumb['url'] . '" width="' . $thumb['width'] . '" height="' . $thumb['height'] . '" style="padding: 10px;"></a>';
20
  }
21
 
22
 return $return;
23
}

The result:

Replace YouTube Links in Text with Embed Code

Again, it's just an example; the point is that you can perform any manner of tricks from the resulting video array.

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment