English 中文(简体)
从YouTube 嵌入代码中提取视频id
原标题:Pulling a video id from YouTube embed code

我正在尝试将 PHP preg_match 表达式移植到 PHP 上, 以便从 YouTube 的 Javascript 嵌入代码中提取一个视频 ID 。 我目前在 PHP 中有此功能 :

$pattern =  %(?:https?://)?(?:www.)?(?:youtu.be/| youtube.com(?:/embed/|/v/|/watch?v=))([w-]{10,12})[a-zA-Z0-9<>"]%x ;
$result = preg_match($pattern, $url, $matches);

我尝试使用以下工具才能用Javascript(Javascript)写成:

var reg = /(?:https?://)?(?:www.)?(?:youtu.be/|youtube.com(?:/embed/|/v/|/watch?v=))([w-]{10,12})/g;
var matches = uploadVideoEmbedCode.match(reg);

我使用的测试数据是:

<iframe width="560" height="315" src="http://www.youtube.com/embed/1NMUDb3Ewhs" frameborder="0" allowfullscreen></iframe>

当我尝试使用上述正则表达式时, 我发现以下错误 :

语法错误: 意外的符号吗?

你将一如既往的帮忙 将是非常感激的。

最佳回答

您需要回避您在regex 中的 < code>/ 鞭笞, 因为它们是分隔符。 如果您想要匹配字面上的 < code>/ , 请使用 < code> / :

var reg = /(?:https?://)?(?:www.)?(?:youtu.be/|youtube.com(?:/embed/|/v/|/watch?v=))([w-]{10,12})/g;

另一个选项是使用 new RegExp(..., g) 而不是 /.../g - 但随后您需要避免每次反斜, 这会更加令人烦恼:

var reg = new RegExp( (?:https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=))([\w-]{10,12}) ,  g );

要最终获得 ID, 请使用 var id = reg. exec( 您的 String) [1]

问题回答

您必须在正则表达式 / 中避免前斜线 。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.