我发现接受答案的代码非常混乱。它也不包括几个小时。我也认为 YouTube 删除了#
URL。我在我的Advanced Responsive Video Embedder WordPress 插件中编写了这个函数。与公认的答案相比,我认为它的编码非常简洁,而且更容易理解。
我希望这会对某人有所帮助。
2019 年更新通知 (int) 部分去掉了 h/m/s 字符。我愿意接受改进的建议。
/**
* Calculates seconds based on youtube times
*
* @author Nicolas Jonas
* @license GPLv3
* @link http://nextgenthemes.com
*
* @param string $yttime The '1h25m13s' part of youtube URLs
*
* @return int Starttime in seconds
*/
function youtube_time_to_seconds( $yttime ) {
$matches['h'] = 0;
$matches['m'] = 0;
$matches['s'] = 0;
$pattern = '/' .
'(?<h>[0-9]+h)?' .
'(?<m>[0-9]+m)?' .
'(?<s>[0-9]+s)?/';
preg_match( $pattern, $yttime, $matches );
return ( (int) $matches['h'] * 60 * 60 ) +
( (int) $matches['m'] * 60 ) +
(int) $matches['s'];
}
参考的旧代码。不考虑案例 1h2s:
/**
* Calculates seconds based on youtube times
*
* @author Nicolas Jonas
* @license GPLv3
* @link http://nextgenthemes.com
*
* @param string $yttime The '1h25m13s' part of youtube URLs
*
* @return int Starttime in seconds
*/
function youtube_time_to_seconds( $yttime ) {
$format = false;
$hours = $minutes = $seconds = 0;
$pattern['hms'] = '/([0-9]+)h([0-9]+)m([0-9]+)s/'; // hours, minutes, seconds
$pattern['ms'] = '/([0-9]+)m([0-9]+)s/'; // minutes, seconds
$pattern['h'] = '/([0-9]+)h/';
$pattern['m'] = '/([0-9]+)m/';
$pattern['s'] = '/([0-9]+)s/';
foreach ( $pattern as $k => $v ) {
preg_match( $v, $yttime, $result );
if ( ! empty( $result ) ) {
$format = $k;
break;
}
}
switch ( $format ) {
case 'hms':
$hours = $result[1];
$minutes = $result[2];
$seconds = $result[3];
break;
case 'ms':
$minutes = $result[1];
$seconds = $result[2];
break;
case 'h':
$hours = $result[1];
break;
case 'm':
$minutes = $result[1];
break;
case 's':
$seconds = $result[1];
break;
default:
return false;
}
return ( $hours * 60 * 60 ) + ( $minutes * 60 ) + $seconds;
}
来源:Github
可以这样使用它:
parse_url
它使用而parse_str
不是正则表达式整个 URLS 来解析 URL 和参数,这是更好和更可靠的方法。
$urls[] = 'http://youtu.be/vrXgLhkv21Y';
$urls[] = 'http://youtu.be/vrXgLhkv21Y?t=foobar';
$urls[] = 'http://youtu.be/vrXgLhkv21Y?foo=bar&t=4s';
$urls[] = 'http://youtu.be/vrXgLhkv21Y?t=1h19m14s';
$urls[] = 'http://youtu.be/vrXgLhkv21Y?t=19m14s';
$urls[] = 'http://youtu.be/vrXgLhkv21Y?t=2h';
$urls[] = 'http://youtu.be/vrXgLhkv21Y?t=5m';
$urls[] = 'http://youtu.be/vrXgLhkv21Y?t=50s';
#extract the part after the &t= in urls and run the function if exists
foreach( $urls as $url ) {
$parsed_url = parse_url( $url );
if ( empty( $parsed_url['query'] ) )
continue;
parse_str( $parsed_url['query'], $args );
if ( empty( $args['t'] ) )
continue;
echo youtube_time_to_seconds( $args['t'] ) . "\n";
}
输出:
4
4754
1154
7200
300
50