![]() |
regex nightmare: anyone want to check it?
My youtube wordpress plugin works via
[!youtube]L1BDM1oBRJ8[/youtube!] I also wanted to be able to do it via https://youtube.com/watch?v=L1BDM1oBRJ8 https://youtube.com/watch?v=L1BDM1oBRJ8 www.youtube.com/watch?v=L1BDM1oBRJ8 youtube.com/watch?v=L1BDM1oBRJ8 watch?v=L1BDM1oBRJ8 v=L1BDM1oBRJ8 L1BDM1oBRJ8 https://youtube.com/v/L1BDM1oBRJ8 Code:
$regex = "/\[(?:(?:http:\/\/)?(?:www\.)?youtube\.com\/)?(?:(?:watch\?)?v=|v\/)?([a-zA-Z0-9\-\_]{11})(?:&[a-zA-Z0-9\-\_]+=[a-zA-Z0-9\-\_]+)*\]/"; |
well, the simplest is to optionally allow each component:
(http:\/\/)?(www\.)?(youtube\.com)?(\/)?(watch\?)?(v=)?([a-zA-Z0-9]{11}) but then this means that any optional component can be left out eg: http://v=L1BDM1oBRJ8 is valid. |
That should work, it might be a little overkill with all the valid character checking though :P
You could also: $arr = explode('=', $youTubeURL); and validate just the portion you want: $linkCode = $arr[count($arr)-1]; While that wouldn't work with the last case you posted you could just do a: $youTubeUrl = str_replace('/', '=', $youTubeUrl); before hand since you don't care what the domain is anyway... It would definitely be much faster than using regex, parsing wise :P |
Running benchmarks on regex (using borked's simplified regex) vs explode (since we're trying to strip the actual value for v...
I show explode method as twice as fast as regex ;) |
All times are GMT -7. The time now is 12:07 AM. |
Powered by vBulletin® Version 3.8.8
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
©2000-, AI Media Network Inc123