Match two regex patterns in one preg_match
Due to limitations in my script, I've come a开发者_StackOverflow中文版cross a problem where I need to make sure a string matches one of two regex patterns while only calling preg_match()
once.
Here's some of my code:
public static function get_file_host_from_link($link)
{
foreach(Filehosts::$file_hosts as $key => $val)
{
if(preg_match("#{$val["regex"]}#", $link))
{
// We have a match, return this file host information
return $key;
}
}
// We've looped through all the file hosts and it hasn't matched,
// return false
return false;
}
Now, the problem with matching Fileserve.com URL's is that there can be two types of valid URL structures. One of them is:
http://www.fileserve.com/file/aHd8AHD
and the other:
http://www.fileserve.com/file/zR8VJVM/file_name.zip
At the moment, I can match the first structure perfectly fine using this regex: ^http://www.fileserve.com/file/[a-zA-Z0-9]+$
but I also need to match the other URL structure using something like this: http://www.fileserve.com/[a-zA-Z0-9]+/[a-zA-Z0-9_-\.]+$
. How can I do this with my existing code and only calling preg_match()
once? I thought about something like this:
(^http://www.fileserve.com/file/[a-zA-Z0-9]+$|http://www.fileserve.com/[a-zA-Z0-9]+/[a-zA-Z0-9_-\.]+$)
which to my knowledge means "match the first regex pattern OR the second one", but I have no idea if that'd work.
Thanks!
The following should work:
^http://www.fileserve.com/file/[a-zA-Z0-9]+(/[-a-zA-Z0-9_\.]+)?$
The ?
after everything in the parentheses makes it optional.
Also, note that the character class [a-zA-Z0-9_-\.]
is invalid because -
specifies a range unless it is escaped or at the start.
You either want [-a-zA-Z0-9_\.]
or [a-zA-Z0-9_\-\.]
(I used the first in my answer).
精彩评论