It's nice to allow end users to post their own videos on my website, but the problem is, the HTML YouTube provides for users to embed video does not validate.
YouTube uses the EMBED tag wrapped by an object tag to embed their videos which is not a standards based way of embeding video. Embeding video is easy and there is no need to resort to YouTubes method.
Rather than put the burden on my end users to properly embed video, I decided to write a function that would convert any videos posted from YouTube and display them in a standards based way.
Converting YouTube's Garbage Embed Code To Valid HTML
-
The function requires that you pass it the user's embed code and a link to the YouTube video
Function YouTubeCleanup(embed,link)
-
Next we check if the embed variable contains the phrase "youtube" in it
if len(replace(embed,"youtube","")) <> len(embed) then
-
Then I build the new path to the YouTube video using the link variable
url = "http://www.youtube.com/v/" & replace(link,"http://www.youtube.com/watch?v=","") & "&hl=en"
-
Next I build the output for the new standards based way of embeding flash video
embed = "<object type=""application/x-shockwave-flash"" data=""" & url & "&hl=en""><param name=""movie"" value=""" & url & """></object>"
-
Finally I return the value of the embed variable. Note that if the embed variable did not initially contain "youtube" in it, it will return the variable's default value and no harm has been done.
YouTubeCleanup = embed
Putting It All Together
Function YouTubeCleanup(embed,link)
if len(replace(embed,"youtube","")) <> len(embed) then
url = "http://www.youtube.com/v/" & replace(link,"http://www.youtube.com/watch?v=","") & "&hl=en"
embed = "<object type=""application/x-shockwave-flash"" data=""" & url & "&hl=en""><param name=""movie"" value=""" & url & """></object>"
end if
YouTubeCleanup = embed
End Function