私はstackoverflowを閲覧していて、ここで素晴らしい正規表現コードを見つけました。YouTubeビデオIDを分離する方法は他にもあるかもしれませんが、学習目的で正規表現を使用することにしました。input1
(以下に示す)の正規表現コードは、&
文字の後のすべてを無視します。これにより、ビデオIDが消去されるため、IDが正しくないか空になります。正規表現が後にすべてをクリアするのはなぜ&
ですか?
エラー:
入力1: http ://www.youtube.com/watch? feature&v = 317a815FLWQ
結果1:http // www.youtube.com / watch?feature
普通:
入力2: http ://www.youtube.com/watch? v=spDj54kf-vY&feature=g-vrec
結果2: http ://www.youtube.com/watch? v=spDj54kf-vY
正規表現コード(元のコメント付き)
$text = preg_replace('~
# Match non-linked youtube URL in the wild. (Rev:20111012)
https?:// # Required scheme. Either http or https.
(?:[0-9A-Z-]+\.)? # Optional subdomain.
(?: # Group host alternatives.
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com followed by
\S* # Allow anything up to VIDEO_ID,
[^\w\-\s] # but char before ID is non-ID char.
) # End host alternatives.
([\w\-]{11}) # $1: VIDEO_ID is exactly 11 chars.
(?=[^\w\-]|$) # Assert next char is non-ID or EOS.
(?! # Assert URL is not pre-linked.
[?=&+%\w]* # Allow URL (query) remainder.
(?: # Group pre-linked alternatives.
[\'"][^<>]*> # Either inside a start tag,
| </a> # or inside <a> element text contents.
) # End recognized pre-linked alts.
) # End negative lookahead assertion.
[?=&+%\w-]* # Consume any URL (query) remainder.
~ix',
'<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>',
$text);
return $text;