George
George

Reputation: 36794

Extract YouTube video ID from embed URL within iFrame tags

I have a certain amount of content like this:

<p><strong>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ullamcorper enim ut nulla fringilla, non elementum nunc dapibus. Donec porta a lorem in vestibulum. Aenean viverra vulputate finibus. Sed malesuada nibh vitae enim luctus, at placerat diam vehicula.</strong></p>

<p>Quisque eu nisl sed tellus congue aliquet ac id risus. Etiam eget nisi ac lectus cursus suscipit. Mauris a dictum justo. Aliquam eget mi vel nunc imperdiet ultricies.</p>

<iframe width="480" height="270" frameborder="0" src="https://www.youtube.com/embed/EgqUJOudrcM" allowfullscreen="" ></iframe>

All I am trying to do is get the YouTube video ID.

So far, I have come up with the following Regular Expression:

/<iframe.*src=["\'].*youtube\.com\/embed\/(.*)["\'] ?>/

This works if the src attribute is the last attribute in the tag, otherwise it doesn't. How can my regular expression be written so as to overcome this?

Works in this case

But not in this one

As you can see, in the second example, my Regex also matches the attribute after src. I know why this happens, I just can't work out how to prevent it.

I'm certainly no Regex expert, so any suggestions to improve what I currently have are welcome.

Upvotes: 0

Views: 1535

Answers (2)

Cyrbil
Cyrbil

Reputation: 6478

With this one:

<iframe.*?src=".*?youtube\.com\/embed\/(\w+)

The .*? avoid matching to much and stop on first src attribute
Then it match the url straightforward.

Edit: You just want the id, not full url

Upvotes: 3

Mayur Koshti
Mayur Koshti

Reputation: 1862

You can use the following regex:

<iframe[^>]*src=\"[^\"]+\/([^\"]+)\"[^>]*>

Upvotes: 1

Related Questions