Validate YouTube video URL format in PHP using parse_url() function



Validate YouTube video URL format in PHP using parse_url() function

<?php
$yt_url = "https://www.youtube.com/watch?v=cCO2tPGa-dM";
$url_parsed_arr = parse_url($yt_url);
?>


Array
(
    [scheme] => https
    [host] => www.youtube.com
    [path] => /watch
    [query] => v=cCO2tPGa-dM&t=49s )
 
<?php
$yt_url = "https://www.youtube.com/watch?v=cCO2tPGa-dM";
$url_parsed_arr = parse_url($yt_url);
if ($url_parsed_arr['host'] == "www.youtube.com" && $url_parsed_arr['path'] == "/watch" && substr($url_parsed_arr['query'], 0, 2) == "v=" && substr($url_parsed_arr['query'], 2) != "") {
echo "The URL is a valid YouTube link";
} else {
echo "Not a valid YouTube link";
}
?>



If the URL is a valid YouTube video page link, it will show “The URL is a valid YouTube link” on the web page, otherwise it will show “Not a valid YouTube link” on the page.








Post a Comment

Previous Post Next Post