programing

preg_match를 사용하여 youtube video id 구문 분석

css3 2023. 10. 12. 23:23

preg_match를 사용하여 youtube video id 구문 분석

저는 preg_match를 이용하여 유튜브 URL의 동영상 ID를 파싱하려고 합니다.이 사이트에서 작동하는 것으로 보이는 정규 표현을 찾았습니다.

(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+

이 사진에 표시된 것과 같이:

alt text

내 PHP는 다음과 같으나 작동하지 않습니다(Unknown modifier '[' error] 제공).

<?
 $subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1";

 preg_match("(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+", $subject, $matches);

 print "<pre>";
 print_r($matches);
 print "</pre>";

?>

건배.

이 정규군은 내가 찾을 수 있는 모든 URL에서 ID를 가져옵니다.더 많은 것이 있을지 모르지만, 어디에서도 그것들에 대한 참고 자료를 찾을 수 없었습니다.일치하지 않는 것을 발견하셨다면 URL과 함께 댓글을 남겨주시면 URL과 일치하도록 regex를 업데이트 해보겠습니다.

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

다음은 이 regex가 일치하는 URL의 샘플입니다. (무시되는 지정된 URL 뒤에 더 많은 컨텐츠가 있을 수 있습니다.)

위와 같은 옵션으로 youtube-nocookie.com URL에서도 작동합니다.

또한 임베디드 코드(iframe 및 객체 태그 모두)의 URL에서 ID를 꺼냅니다.

URL 및 쿼리 문자열을 더 잘 사용하고 구문 분석합니다.

$subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1";
$url = parse_url($subject);
parse_str($url['query'], $query);
var_dump($query);

저는 몇 주 전에 작성한 PHP 클래스에 대해 이 문제를 처리해야 했고 결국 어떤 종류의 문자열과 일치하는 regex를 사용하게 되었습니다.URL 스킴 유무, 서브도메인 유무, youtube.com URL 문자열, youtu.be URL 문자열 및 모든 종류의 파라미터 정렬을 처리합니다.GitHub에서 확인하거나 아래의 코드 블록을 복사하여 붙여넣기만 하면 됩니다.

/**
 *  Check if input string is a valid YouTube URL
 *  and try to extract the YouTube Video ID from it.
 *  @author  Stephan Schmitz <eyecatchup@gmail.com>
 *  @param   $url   string   The string that shall be checked.
 *  @return  mixed           Returns YouTube Video ID, or (boolean) false.
 */        
function parse_yturl($url) 
{
    $pattern = '#^(?:https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=|/watch\?.+&v=))([\w-]{11})(?:.+)?$#x';
    preg_match($pattern, $url, $matches);
    return (isset($matches[1])) ? $matches[1] : false;
}

regex에 대해 설명하자면, 여기에 엎질러진 버전이 있습니다.

/**
 *  Check if input string is a valid YouTube URL
 *  and try to extract the YouTube Video ID from it.
 *  @author  Stephan Schmitz <eyecatchup@gmail.com>
 *  @param   $url   string   The string that shall be checked.
 *  @return  mixed           Returns YouTube Video ID, or (boolean) false.
 */        
function parse_yturl($url) 
{
    $pattern = '#^(?:https?://)?';    # Optional URL scheme. Either http or https.
    $pattern .= '(?:www\.)?';         #  Optional www subdomain.
    $pattern .= '(?:';                #  Group host alternatives:
    $pattern .=   'youtu\.be/';       #    Either youtu.be,
    $pattern .=   '|youtube\.com';    #    or youtube.com
    $pattern .=   '(?:';              #    Group path alternatives:
    $pattern .=     '/embed/';        #      Either /embed/,
    $pattern .=     '|/v/';           #      or /v/,
    $pattern .=     '|/watch\?v=';    #      or /watch?v=,    
    $pattern .=     '|/watch\?.+&v='; #      or /watch?other_param&v=
    $pattern .=   ')';                #    End path alternatives.
    $pattern .= ')';                  #  End host alternatives.
    $pattern .= '([\w-]{11})';        # 11 characters (Length of Youtube video ids).
    $pattern .= '(?:.+)?$#x';         # Optional other ending URL parameters.
    preg_match($pattern, $url, $matches);
    return (isset($matches[1])) ? $matches[1] : false;
}

리더답변에서 정규군을 완성했습니다.또한 다양한 URL에서 ID를 가져오지만 더 정확합니다.

if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[\w\-?&!#=,;]+/[\w\-?&!#=/,;]+/|(?:v|e(?:mbed)?)/|[\w\-?&!#=,;]*[?&]v=)|youtu\.be/)([\w-]{11})(?:[^\w-]|\Z)%i', $url, $match)) {
    $video_id = $match[1];
}

또한 11자 이상의 잘못된 ID를 올바르게 처리합니다.

http://www.youtube.com/watch?v=0zM3nApSvMgDw3qlxF

사용하다

 preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+#", $subject, $matches);

슬래시 문자를 피하는 것을 잊으셨군요.그래서 이 사람이 해야 할 일은 다음과 같습니다.

preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]\/)[^&\n]+|(?<=v=)[^&\n]+#", $subject, $matches);

BBcode에 대한 Parse Start 매개변수(https://developers.google.com/youtube/player_parameters#start)

:[yt]http://www.youtube.com/watch?v=G059ou-7wmo#t=58[/yt]

PHP 정규 표현식:

'#\[yt\]https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=|/ytscreeningroom\?v=|/feeds/api/videos/|/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[?=#&+%\w-]*(t=(\d+))?\[/yt\]#Uim'

바꾸기:

'<iframe id="ytplayer" type="text/html" width="639" height="360" src="http://www.youtube.com/embed/$1?rel=0&vq=hd1080&start=$3" frameborder="0" allowfullscreen></iframe>'

PHP 오류에 대해 직접적으로 언급하는 사람을 보지 못해서 설명해보겠습니다.

알 수 없는 수식어 '[']' 오류가 발생하는 이유는 정규식을 구분 기호로 묶는 것을 잊어버렸기 때문입니다.PHP는 영숫자가 아닌 공백이 아닌 ASCII 문자인 한 첫 번째 문자를 구분 기호로 사용합니다.당신의 레지렉스에서:

preg_match("(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+", $subject, $matches);

PHP는 당신이 의미하는 것이라고 생각합니다.(첫 번째 구분자 구분 그런 다음에는 종결 구분 기호라고 생각되는 것을 찾습니다찾습니다.)그리고 다음이 패턴 수정자라고 가정합니다. 첫 첫 자 을 알 수 있습니다.) ,[.[는 분명히 유효한 패턴 수정자가 아니며, 따라서 오류가 발생합니다.

해결책은 단순히 regex를 구분 기호로 감싸고 문자 그대로 일치시키려는 regex 내의 구분 기호를 모두 제거하는 것입니다.사용하는것을 좋아합니다~로서 b/c다와 일치시킬 가 거의 .~

아래 코드를 사용

$url = "" // here is url of youtube video
$pattern = getPatternFromUrl($url); //this will retun video id

function getPatternFromUrl($url)
{
$url = $url.'&';
$pattern = '/v=(.+?)&+/';
preg_match($pattern, $url, $matches);
//echo $matches[1]; die;
return ($matches[1]);
}

저한테는 효과가 있었어요

$yout_url='http://www.youtube.com/watch?v=yxYjeNZvICk&blabla=blabla';

$videoid = preg_replace("#[&\?].+$#", "", preg_replace("#http://(?:www\.)?youtu\.?be(?:\.com)?/(embed/|watch\?v=|\?v=|v/|e/|.+/|watch.*v=|)#i", "", $yout_url));

언급URL : https://stackoverflow.com/questions/2936467/parse-youtube-video-id-using-preg-match