2015-01-15 37 views
1

我有一個字符串這樣的:正則表達式查找YouTube鏈接字符串

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, https://www.youtube.com/watch?v=7TL02DA5MZM when an unknown printer took a galley of type and scrambled it to make a type 

這是我有:

preg_match("(?:http://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch\?)?([^\s]+?)", $content, $m); 
    var_dump($m); 

,並要提取Youtube鏈接形成的。 視頻ID也可以。

不勝感激!

回答

3

這會爲你工作,

\S*\bwww\.youtube\.com\S* 

\S*匹配零個或多個非空格字符。

代碼將是,

preg_match('~\S*\bwww\.youtube\.com\S*~', $str, $matches); 

DEMO

和我做了一些修改,以你原來的正則表達式。

(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch\?v=)?([^\s]+) 

DEMO

$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, https://www.youtube.com/watch?v=7TL02DA5MZM when an unknown printer took a galley of type and scrambled it to make a type"; 
preg_match('~(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch\?v=)?([^\s]+)~', $str, $match); 
print_r($match); 

輸出:

Array 
(
    [0] => https://www.youtube.com/watch?v=7TL02DA5MZM 
    [1] => 7TL02DA5MZM 
) 
+0

我得到您的正則表達式錯誤:未知修飾符'?'在 – user998163 2015-01-15 17:24:41

+0

看到我的更新..它適用於我。我想你忘了添加分隔符。 – 2015-01-15 17:27:39

+0

它忽略了youtu.be(ex.https://youtu.be/NFD1dtTosQc) – user998163 2015-01-15 17:36:46

2
(?:https?:\/\/)?www\.youtube\.com\S+?v=\K\S+ 

你可以通過匹配YouTube網址,然後使用\K。看到演示丟棄獲取的視頻ID。

https://regex101.com/r/tX2bH4/21

$re = "/(?:https?:\\/\\/)?www\\.youtube\\.com\\S+?v=\\K\\S+/i"; 
$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, https://www.youtube.com/watch?v=7TL02DA5MZM when an unknown printer took a galley of type and scrambled it to make a type"; 

preg_match_all($re, $str, $matches); 
+0

差不多。那麼youtu.be呢? – user998163 2015-01-15 17:20:57

+0

@ user998163(?:youtube \ .com | youtu \ .be)使用此地址YouTube \ .com – vks 2015-01-15 17:26:08

+0

您可以更新您的重播嗎?我試過(?:youtube \ .com | youtu \ .be)但沒有成功。 – user998163 2015-01-15 17:29:28

0

我想出了下面的正則表達式:

https?:\/\/(w{3}\.)?youtube\.com\/watch\?.+?(\s|$) 

這裏是我如何使用這個:

$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, https://www.youtube.com/watch?v=7TL02DA5MZM when an unknown printer took a galley of type and scrambled it to make a type"; 

preg_match("/https?:\/\/(w{3}\.)?youtube\.com\/watch\?.+?(\s|$)/", $str, $matches); 

$ytube = $matches[0]; 
$parse = parse_url($ytube); 
parse_str($parse["query"], $query); 

echo $ytube; 
print_r($parse); 
print_r($query); 

這裏是的輸出物品:

https://www.youtube.com/watch?v=7TL02DA5MZM 
Array 
(
    [scheme] => https 
    [host] => www.youtube.com 
    [path] => /watch 
    [query] => v=7TL02DA5MZM 
) 
Array 
(
    [v] => 7TL02DA5MZM 
) 
相關問題