Regular Expression: Converting Youtube Video Watch URL to Embed URL

A YouTube video URL may be encountered in a variety of formats:

latest short format:
iframe (secure):
object param:
object embed:
more params:

Here is a PHP function with a commented regex that matches each of these URL forms and converts them to links (if they are not links already):

And Here is a JavaScript version with the exact same regex (with comments removed):


  • The VIDEO_ID portion of the URL is captured in the one and only capture group: $1.
  • If you know that your text does not contain any pre-linked URLs, you can safely remove the negative lookahead assertion which tests for this condition (The assertion beginning with the comment: “Assert URL is not pre-linked.”) This will speed up the regex somewhat.
  • The replace string can be modified to suit. The one provided above simply creates a link to the generic "" style URL and sets the link text to: "YouTube link: VIDEO_ID".

Below regex includes above aggressive approach as a last resort, but attempts all common matchings first, vastly reducing the possibility of a wrong match later in the URL.

Handles all of the cases originally referenced in ridgerunners examples, plus any url that might happen to have an 11 character sequence later in the url. ie:

Here is a working sample that tests all of the sample YouTube urls:

Here’s a PHP method provided for a project that extracts Youtube and Vimeo video keys:

  1. Find a regex that will extract all links from a text. Google will help you there.
  2. Loop all the links and call getHostInfo() for each