-3

重複の可能性:
preg_matchを使用してYouTubeビデオIDを解析します

$message = "this is an youtube video http://www.youtube.com/watch?v=w6yF_UV1n1o&feature=fvst i want only the id";

$message = preg_replace('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', '\\1', $message);

print $message;

上記のプリント...

this is an youtube video http://www.w6yF_UV1n1o&feature=fvst i want only the id

私が欲しいのは:

this is an youtube video w6yF_UV1n1o i want only the id

前もって感謝します :)

4

1 に答える 1

1

最初に有効なURLを照合し、次にそのURLから有効なYouTube IDを抽出してから、見つかった元のURLを一致するIDに置き換えます(有効なIDが見つかった場合)。

<?php

$message = "
    this is a youtube video http://www.youtube.com/watch?v=w6yF_UV1n1o&feature=fvst i want only the id
    this is not a youtube video http://google.com do nothing
    this is an youtube video http://www.youtube.com/watch?v=w6yF_UV1n1o&feature=fvst i want only the id
";

preg_match_all('#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#', $message, $matches);

if (isset($matches[0]))
{
    foreach ($matches[0] AS $url)
    {
        if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $matches))
            $message = str_replace($url, $matches[1], $message);
    }
}

echo $message;

出典:http : //daringfireball.net/2009/11/liberal_regex_for_matching_urls&https : //stackoverflow.com/a/6382259/1748964

于 2012-10-21T23:45:51.543 に答える