I would like to parse a youtube url using XSLT and get only the Video ID from that URL. What's the best way to do this using XSLT?
So, if the url is: http://www.youtube.com/watch?v=qadqO3TOvbQ&feature=channel&list=UL
I only want qadqO3TOvbQ
and put it into an embed code:
<iframe width="560" height="315" src="http://www.youtube.com/embed/qadqO3TOvbQ" frameborder="0" allowfullscreen=""></iframe>
I. This XPath 2.0 expression:
substring-after(tokenize($pUrl, '[?|&]')[starts-with(., 'v=')], 'v=')
produces the wanted, correct result.
Alternatively, one can use the slightly shorter:
tokenize(tokenize($pUrl, '[?|&]')[starts-with(., 'v=')], '=')[2]
Here is a complete XSLT 2.0 transformation:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:param name="pUrl" select=
"'http://www.youtube.com/watch?v=qadqO3TOvbQ&feature=channel&list=UL'"/>
<xsl:template match="/">
<xsl:sequence select=
"tokenize(tokenize($pUrl, '[?|&]')[starts-with(., 'v=')], '=')[2]"/>
</xsl:template>
</xsl:stylesheet>
When this transformation is applied on any XML document (not used), the wanted, correct result is produced:
qadqO3TOvbQ
II. This XPath 1.0 expression:
concat
(substring-before(substring-after(concat($pUrl,'&'),'?v='),'&'),
substring-before(substring-after(concat($pUrl,'&'),'&v='),'&')
)
produces the wanted result.
Do note:
Both solutions extract the wanted string even if the query string parameter named v
isn't the first one or even in the case when it is the last one.
XSLT/XPath is not best suited to string handling (1.0 especially) but you can achieve what you need by mixing up the substring-after()
and substring-before()
functions:
<xsl:value-of select="substring-before(substring-after($yt_url, '?v='), '&feature')" />
(assumes the YT URL is stored in an XSLT var, $yt_url
, and that it has its &
escaped to &
).
Demo at this this XML Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With