如何查找文本中是否有youtube嵌入代码


How to find if there is youtube embed code in the text

我想搜索文本中是否有youtube嵌入代码。我正在使用wordpress,想在帖子内容中找到youtube嵌入代码。做任何一个主体都可以给我提供php正则表达式来查找是否有youtube嵌入的代码在文本中找到。谢谢

您可以通过在the_content中添加过滤器来找到它。

注意:只有在模板中使用the_content进行渲染时,它才会起作用

将以下代码放入functions.php中,并根据需要修改if条件。

function find_youtube_wp_content( $content ) {
        $regex = '~(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch'?v=)?([^'s]+)~';
        preg_match( $regex, $content, $match );
        if ( ! empty( $match ) && isset( $match[0] ) ) {
            echo $match[0];
        } else {
        }
    }
add_filter( 'the_content', 'find_youtube_wp_content' );

我使用这个代码,它可以工作

$regex = '/https?:'/'/')?(?:www.)?(?:youtube.com|youtu.be)'/embed'//';
        preg_match( $regex, $post->post_content, $match );
        if ( ! empty( $match ) && isset( $match[0] ) ) {
            echo $match[0];
        } else {
        }