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


Integrate this regex code into existing php code

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

$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>';

URL在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'.

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

上面错误中的URL应该这样格式化:www.youtube.com/embed/l4X2hQC32NA?rel=0

所以,我找到了一种方法来动态地改变格式的代码如下:
$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的格式。谁能告诉我怎么才能做到这一点?

像这样:

$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