Log in

View Full Version : RegEx in Custom Profile Field


Digital Jedi
01-23-2011, 02:16 PM
Having only worked with RegExes in AME, I see that vB handles them a bit differently. I want a Regex that matches typical YouTube URLs along with the extra stings that come along with them. I tried my Regex for my AME YouTube definition:

^http://[\w.]+youtube\.[\w]+/watch[\?\#!]+v=([\w-]+)[\w&;+=-]*[\#t=]*([\d]*)[&;10shdq=]*|^$

But vB gives me a preg-match error with the exclamation point in there. Didn't work escaping it, either. AME has it's own quirks with Regex, and that's where I learned how to do them. But I suspect that vB does it a little differently. This needs to match these kinds of URLs:

http://www.youtube.com/watch?v=is_b1ahWN3Q
http://www.youtube.com/watch?&v=is_b1ahWN3Q
http://www.youtube.com/watch#!v=is_b1ahWN3Q
http://www.youtube.com/watch?v=is_b1ahWN3Q&some_string=also_with_special_characters_&;+=-

And deep linking examples.

http://www.youtube.com/watch?v=is_b1ahWN3Q#t=5m
http://www.youtube.com/watch?v=is_b1ahWN3Q#t=5m7s
http://www.youtube.com/watch?v=is_b1ahWN3Q#t=120s

Or just be blank. Maybe my matches don't need to be this specific?

kh99
01-23-2011, 02:58 PM
This seems to work:


<?php
$pat = '@^http://[\w.]+youtube\.[\w]+/watch[\?\#!]+v=([\w-]+)[\w&;+=-]*[\#t=]*([\d]*)[&;10shdq=]*|^$@';

$strs = array('http://www.youtube.com/watch?v=is_b1ahWN3Q',
'http://www.youtube.com/watch?&v=is_b1ahWN3Q',
'http://www.youtube.com/watch#!v=is_b1ahWN3Q',
'http://www.youtube.com/watch?v=is_b1ahWN3Q&some_string=also_with_special_characters_&;+=-',
'http://www.youtube.com/watch?v=is_b1ahWN3Q#t=5m',
'http://www.youtube.com/watch?v=is_b1ahWN3Q#t=5m7s',
'http://www.youtube.com/watch?v=is_b1ahWN3Q#t=120s',
);


foreach ($strs as $str)
{
preg_match($pat, $str, $matches);
print_r($matches);
echo("<BR /><BR />\n");
}
?>


and I get this output:

Array ( [0] => http://www.youtube.com/watch?v=is_b1ahWN3Q [1] => is_b1ahWN3Q [2] => )

Array ( )

Array ( [0] => http://www.youtube.com/watch#!v=is_b1ahWN3Q [1] => is_b1ahWN3Q [2] => )

Array ( [0] => http://www.youtube.com/watch?v=is_b1ahWN3Q&some_string=also_with_special_characters_&;+=- [1] => is_b1ahWN3Q [2] => )

Array ( [0] => http://www.youtube.com/watch?v=is_b1ahWN3Q#t=5 [1] => is_b1ahWN3Q [2] => 5 )

Array ( [0] => http://www.youtube.com/watch?v=is_b1ahWN3Q#t=5 [1] => is_b1ahWN3Q [2] => 5 )

Array ( [0] => http://www.youtube.com/watch?v=is_b1ahWN3Q#t=120s [1] => is_b1ahWN3Q [2] => 120 )


It seems the second string doesn't match because the pattern doesn't allow for & where it appears in that string.