将此正则表达式代码集成到现有的PHP代码中

时间:2014-03-26 18:45:05

标签: javascript php regex video youtube

我使用下面的代码输出嵌入最新视频的视频:

$args = array( 
    'numberposts' => '1', 
    'tax_query' => array(
        array(
            'taxonomy' => 'post_format',
            'field' => 'slug',
            'terms' => 'post-format-video'
        )
    ),
    'meta_query' => array(
        array(
            'key' => 'dt_video',
            'value' => '',
            'compare' => '!='
        )
    )
);
$latest_video = wp_get_recent_posts($args); // Get latest video in 'video' post format
$latest_video_id = $latest_video['0']['ID']; // Get latest video ID
$video_url = htmlspecialchars(get_post_meta($latest_video_id, 'dt_video', true));
echo '<iframe width="180" height="101" src="'.$video_url.'?rel=0&output=embed" frameborder="0" allowfullscreen></iframe>';

HTML输出正常,但视频无法显示,我在控制台中收到以下错误:

Refused to display 'http://www.youtube.com/watch?v=l4X2hQC32NA&feature=g-all-u&context=G258729eFAAAAAAAAHAA?rel=0' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

通过一些搜索,我发现这是因为视频的格式不正确。

上述错误中的网址格式应为:www.youtube.com/embed/l4X2hQC32NA?rel=0

所以,我found a way使用以下代码动态更改格式:

$text = $post->text;
    $search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*<\/a>#x';
    $replace = '<iframe width="180" height="101" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe>';
    $text = preg_replace($search, $replace, $text);
echo $text;

但是,我不确定如何将其实现到原始代码中,以便我可以更改输出URL的格式。有人能告诉我如何实现这个目标吗?

1 个答案:

答案 0 :(得分:1)

像这样:

$video_url = "http://www.youtube.com/watch?v=l4X2hQC32NA&feature=g-all-u&context=G258729eFAAAAAAAAHAA?rel=0";
$search  = '#(?:href="https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch?.*?v=))([\w\-]{10,12}).*$#x';
$replace = "http://www.youtube.com/embed/$1";
preg_match_all($search, $video_url, $matches);
$embedded_video_url = preg_replace($search, $replace, $video_url) ;
echo '<iframe width="180" height="101" src="'.$embedded_video_url.'" frameborder="0" allowfullscreen></iframe>';

只需使用您自己的$video_url

即可