Reputation: 308
I'm trying this on Wordpress, i succeeded to convert the URL of youtube to be embed, but what i'm trying to do is to check first if the url is embed then leave it and if it's not well then it should be converted to embed, the convert part is done, my problem is that i don't know how to compare, i tried this:
$video = $user_details->get('embed_code');
$search = '#(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x';
$replace = 'http://www.youtube.com/embed/$2';
if(!preg_match($search,$video)){
$url_video = preg_replace($search,$replace,$video);
$url_final = '<iframe width="560" height="315" src="'.$url_video.'" frameborder="0" allowfullscreen></iframe>';
}
<div class="youtube_cls">
<?php echo $url_final; ?>
</div>
so i'm trying to use preg_match
but i don't think it works, any ideas how to compare if the $video
is format like the $search
if not convert it and if YES then leave it ?
Upvotes: 0
Views: 386
Reputation: 72855
Your code actually works great -- just that if your match doesn't match, $url_final
isn't getting set.
Swap the comment on $video
to see both echoing properly under $url_final
.
$video = "http://www.youtube.com/watch?v=XUdt_aBmkwo";
//$video = '<iframe width="560" height="315" src="//www.youtube.com/embed/XUdt_aBmkwo" frameborder="0" allowfullscreen></iframe>';
$search = '#(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x';
$replace = 'http://www.youtube.com/embed/$2';
$url_final = $video; //set $url_final to $video so if !preg_match, it still returns
if(!preg_match($search,$video))
{
$url_video = preg_replace($search,$replace,$video);
$url_final = '<iframe width="560" height="315" src="'.$url_video.'" frameborder="0" allowfullscreen></iframe>';
}
echo $url_final;
Upvotes: 1