从字符串中提取youtube URL


extracting a youtube URL from a string

到目前为止我尝试的是这个函数:

function isYoutubeUrl($url) {
    return preg_match("#^https?://(?:www'.)?youtube.com#", $url);
}

但它只适用于像这样的普通youtube字符串:

$string = 'http://www.youtube.com/watch?v=bJIXm6U4df';
$newString = isYoutubeURL($string);
if($newString); // true

我需要一个函数来检查一个字符串的youtube URL,如果有一个,返回URL。

$string = 'this is so crazy...http://www.youtube.com/watch?v=bJIXm6U4df';
$newString = extractYoutubeUrl($string);
echo $newString; // http://www.youtube.com/watch?v=bJIXm6U4df

任何想法?

^ -从字符串开始检查-删除它并尝试

返回preg_match("# https ?://(?: www。)? youtube.com ", $ url);

这将是你的功能:

function extractYoutubeUrl($url) {
    return preg_match("#https?://(?:www'.)?youtube.com#", $url);
}

试试这个

function extractYoutubeUrl($url) {
  if(preg_match("#(http://www'.youtube'.com/watch'?v=[%&=#'w-]*)#", $url, $result))
    return $result[0];
  return null;
}