Search code examples
phpregexyoutubepreg-replacepreg-match

Preg_Replace YouTube URL with or without Start Time Variable


In a shout/post area of my site I allow users to post YouTube URLs using the following regular expression and preg_replace. This works unless the YouTube URL has additional variables such as a start time. I've researched it a lot on Google and StackOverflow but can't find any working examples.

I have also tried preg_match to pull both the video ID and start time and then preg_replace the URL with the variables from the preg_match but had no success with that either.

An example of a video with a start time is: https://youtu.be/PZb9T-eTOcg?t=2m8s

The regular expression in my code below would pull PZb9T-eTOcg?t=2m8s from the URL before replacing it.

Thanks for your help!

        $text = preg_replace('#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#','<br /><div class="cover overlay hover" style="height: 240px;"><img src="https://img.youtube.com/vi/$1/0.jpg" alt="music" class="img-responsive"><a title="YouTube Video" href="https://www.youtube.com/embed/$1?autoplay=1" class="overlay overlay-full overlay-hover overlay-bg-black video" style="height: 240px;"><span class="v-center"><span class="btn btn-lg btn-circle btn-white"><i class="fa fa-play"></i></span></span></a></div>', $text);

Solution

  • Use parse_url() instead.

    The $result of this function, will allow you to get $result['path'] and $result['query'].

    Then, you can use explode('&', $qs) to separate querystring parameters from $result['query'].

    Finally you can use a loop & explode('=', $qsp) again, then switch() to take actions for every query string parameter.