preg_match를 사용하여 YouTube 동영상 ID 구문 분석
preg_match를 사용하여 YouTube URL의 동영상 ID를 파싱하려고합니다. 이 사이트에서 작동하는 것처럼 보이는 정규 표현식을 찾았습니다.
(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+
이 그림에 표시된대로 :
내 PHP는 다음과 같지만 작동하지 않습니다 (알 수없는 수정 자 '['오류 발생) ...
<?
$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과 일치하도록 정규식을 업데이트하겠습니다.
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
$video_id = $match[1];
}
다음은이 정규식이 일치하는 URL의 샘플입니다. (주어진 URL 뒤에 무시되는 콘텐츠가 더있을 수 있음)
- http://youtu.be/dQw4w9WgXcQ ...
- http://www.youtube.com/embed/dQw4w9WgXcQ ...
- http://www.youtube.com/watch?v=dQw4w9WgXcQ ...
- http://www.youtube.com/?v=dQw4w9WgXcQ ...
- http://www.youtube.com/v/dQw4w9WgXcQ ...
- http://www.youtube.com/e/dQw4w9WgXcQ ...
- http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ ...
- http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ ...
- http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ ...
- http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ ...
위와 동일한 옵션으로 youtube-nocookie.com URL에서도 작동합니다.
또한 소스 코드 (iframe 및 객체 태그 모두)의 URL에서 ID를 가져옵니다.
URL 및 쿼리 문자열을 더 잘 사용 parse_url
하고 parse_str
구문 분석합니다.
$subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1";
$url = parse_url($subject);
parse_str($url['query'], $query);
var_dump($query);
몇 주 전에 작성한 PHP 클래스에서이 문제를 처리해야했고 모든 종류의 문자열과 일치하는 정규식으로 끝났습니다. 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;
}
정규식을 설명하기 위해 다음은 유출 된 버전입니다.
/**
* 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);
Parse Start parameter for BBcode (https://developers.google.com/youtube/player_parameters#start)
example: [yt]http://www.youtube.com/watch?v=G059ou-7wmo#t=58[/yt]
PHP regex:
'#\[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'
replace:
'<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>'
I didn't see anyone directly address the PHP error, so I'll try to explain.
The reason for the "Unknown modifier '['" error is that you forgot to wrap your regex in delimiters. PHP just takes the first character as a delimiter, so long as it's a non-alphanumeric, non-whitespace ASCII character. So in your regex:
preg_match("(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+", $subject, $matches);
PHP thinks you meant (
as an opening delimiter. It then finds what it thinks is your closing delimiter, the next )
and assumes what follows are pattern modifiers. However it finds that your first pattern modifier, the next character after the first )
, is [
. [
is obviously not a valid pattern modifier, which is why you get the error that you do.
The solution is to simply wrap your regex in delimiters and make sure any delimiters within the regex that you want to match literally are escaped. I like to use ~
as delimiters, b/c you rarely need to match a literal ~
in a regex.
use below code
$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]);
}
this worked for me.
$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
'Development Tip' 카테고리의 다른 글
개발자가 알아야 할 유용한 비트 연산자 코드 트릭은 무엇입니까? (0) | 2020.11.25 |
---|---|
어댑터에서 활동을 시작하는 방법은 무엇입니까? (0) | 2020.11.25 |
import sun.misc.BASE64Encoder 결과 Eclipse에서 컴파일 오류 발생 (0) | 2020.11.25 |
g ++ 컴파일 시간을 단축하는 방법 (많은 템플릿을 사용할 때) (0) | 2020.11.24 |
공개적으로는 읽기 전용이지만 전용 setter가있는 Objective-C 속성 (0) | 2020.11.24 |