I'm trying to pull a youtube ID from a link like this;
<img src="http://img.youtube.com/vi/OZ3jyvM0jZc/2.jpg" alt="" />
I've only 开发者_C百科been successful in taking out the ID, but not actually getting it!
<cfset ytID = '<img src="http://img.youtube.com/vi/0Z3jyvM0jZc/2.jpg" alt="" />' />
#reReplace(referer,"(vi=?(\=|\/))([-a-zA-Z0-9_]+)|(vi=\/)([-a-zA-Z0-9_]+)", "\1", "one")#
Output: <img src="http://img.youtube.com/vi//2.jpg" alt="" />
RegEx is not my friend today. What am I missing?
Thanks!
Try with regex:
vi\/([^\/]+) // 0Z3jyvM0jZc
You don't need to escape the forward slashes in CFML regex patterns. So take what The Mask has and use whichever method you prefer (both of these only work if the string is indeed a match):
<cfset ytID = '<img src="http://img.youtube.com/vi/0Z3jyvM0jZc/2.jpg" alt="" />'>
<cfoutput>
<pre>
<cfset sLenPos=REFind("/vi/([^/]+)", ytID, 1, "True")>
#mid(ytID, sLenPos.pos[2], sLenPos.len[2])# == OZ3jyvM0jZc
#reReplace(ytID,".*/vi/([^/]+)/.*", "\1")# == OZ3jyvM0jZc
</pre>
</cfoutput>
The key to keeping this simple is using the [^/]+
to match one or more characters that aren't /
I think regex might be the wrong tool for this job. How about using lists?
<cfset ytStr = '<img src="http://img.youtube.com/vi/0Z3jyvM0jZc/2.jpg" alt="" />'>
<cfset ytID = ListGetAt(ytStr, 4, '/')>
<cfset ytID = '<img src="http://img.youtube.com/vi/0Z3jyvM0jZc/2.jpg" alt="" />'>
<cfset sLenPos=REFind("(vi=?(\=|\/))([-a-zA-Z0-9_]+)|(vi=\/)([-a-zA-Z0-9_]+)", ytID, 1, "True")>
<cfoutput>
#mid(ytID, sLenPos.pos[1], sLenPos.len[1])#
</cfoutput>
精彩评论