忽略视频 URL 中的换行符
Ignoring line breaks in video URLs
我想用 iframe 替换 YouTube URLs。因此,我正在使用从不同网站复制的正则表达式,该正则表达式从 YouTube URLs.
获取视频 ID
它不能很好地工作。如果有换行符,则不会占用整个视频 ID。此外,它不会从 URL.
中获取 &feature=share
例如:
输入:
http://www.youtube.com/attribution_link?a=_NDwn20sMog&u=/watch?v=zl-GC1
6vBm4&feature=share
正则表达式:
/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|attribution_link\?a=.+?watch.+?v(?:%|=)|watch\?(?:\S*?&?v\=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})/i
输出:
Array
(
[0] => zl-GC1
)
Array
(
[0] => http://www.youtube.com/attribution_link?a=_NDwn20sMog&u=/watch?v=zl-GC1
)
通过擦除潜在的空格然后匹配来简化。
这是我的意思的一个例子...
<?php
$test = <<<TEST
http://www.youtube.com/attribution_link?a=_NDwn20sMog&u=/watch?v=zl-GC1
6vBm4&feature=share
TEST;
$test = preg_replace('/\s/', '', $test); // NOTE: Scrub potential whitespace.
// NOTE: (&.*)* added to the end of the original pattern to match the
// rest of the query string if any.
preg_match('/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|attribution_link\?a=.+?watch.+?v(?:%|=)|watch\?(?:\S*?&?v\=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})(&.*)*/', $test, $matches);
var_dump($matches);
?>
...,输出:
array(3) {
[0]=>
string(90) "http://www.youtube.com/attribution_link?a=_NDwn20sMog&u=/watch?v=zl-GC16vBm4&feature=share"
[1]=>
string(11) "zl-GC16vBm4"
[2]=>
string(14) "&feature=share"
}
您可以在 Ideone demo 中测试此方法。
我想用 iframe 替换 YouTube URLs。因此,我正在使用从不同网站复制的正则表达式,该正则表达式从 YouTube URLs.
获取视频 ID它不能很好地工作。如果有换行符,则不会占用整个视频 ID。此外,它不会从 URL.
中获取&feature=share
例如:
输入:
http://www.youtube.com/attribution_link?a=_NDwn20sMog&u=/watch?v=zl-GC1
6vBm4&feature=share
正则表达式:
/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|attribution_link\?a=.+?watch.+?v(?:%|=)|watch\?(?:\S*?&?v\=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})/i
输出:
Array
(
[0] => zl-GC1
)
Array
(
[0] => http://www.youtube.com/attribution_link?a=_NDwn20sMog&u=/watch?v=zl-GC1
)
通过擦除潜在的空格然后匹配来简化。
这是我的意思的一个例子...
<?php
$test = <<<TEST
http://www.youtube.com/attribution_link?a=_NDwn20sMog&u=/watch?v=zl-GC1
6vBm4&feature=share
TEST;
$test = preg_replace('/\s/', '', $test); // NOTE: Scrub potential whitespace.
// NOTE: (&.*)* added to the end of the original pattern to match the
// rest of the query string if any.
preg_match('/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|attribution_link\?a=.+?watch.+?v(?:%|=)|watch\?(?:\S*?&?v\=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})(&.*)*/', $test, $matches);
var_dump($matches);
?>
...,输出:
array(3) {
[0]=>
string(90) "http://www.youtube.com/attribution_link?a=_NDwn20sMog&u=/watch?v=zl-GC16vBm4&feature=share"
[1]=>
string(11) "zl-GC16vBm4"
[2]=>
string(14) "&feature=share"
}
您可以在 Ideone demo 中测试此方法。