I have a webapp, where people signup and get a sub domain und开发者_运维知识库er this app domain ( xx.app.com ) ... for each subdomain there is a db that is attached to it grammatically and have the same name as the subdomain.
what i need is the right regex that works with the subdomain and off course a db name ( mysql if it matters ), it's supposed to be lowercase & the length between 6 and 20 and the only allowed character is the " - ", also numbers are banned ...
i tried many times but it always go bad, .. some like : /([a-z-]){6,20}/
Thanks in advance :)
There might be a right regex for this, but regex isn't right for this.
Try parse_url
Edit:
I am not sure how you are using it. If you are only processing the subdomain part, the following should work and not match numbers:
^[a-z-]{6,20}$
This ensures that the subdomain has only a to z and - and between 6 and 20 times. The ^ matches the beginning of the string and $ matches the end.
The reason the earlier regex was accepting numbers or anything else too was because the match itself would have been a part of the string. Now with the ^
and $
you are ensuring that it is the entire string.
This would be a safer regex, since a subdomain cannot start with an hyphen:
^[a-z][a-z-]{5,19}$
As for the database name I believe it cannot contain an hyphen since it is the subtraction operator, so your best choice might be to either disallow hypens or replace them with underscores:
$database = str_replace('-', '_', $subdomain);
EDIT: Apparently @nikic is right, you can use hyphens as long as you backtick the database name.
Have you tried escaping the hyphen?
/([a-z\-]){6,20}/
You will need positive lookahead regex for this. Try following code:
<?php
$a = array("xx-yyy.domain.cam", "xx4yyy.domain.cam", "abcde.domain.com", "my-sub-domain.domain.org");
foreach ($a as $v) {
echo "For domain $v: ";
preg_match('/^(?:[-a-z]{6,20})(?=\.)/', $v, $m );
if (count($m) > 0)
echo( "subdomain: " . $m[0] . "\n");
else
echo "subdomain not matched\n";
}
?>
Basically match combination of lower case alphabets and hyphen -
character of 6 to 20 character length before appearance of first dot .
character.
-
hyphen need not be escaped if used at the start in square brackets.
OUTPUT
For domain xx-yyy.domain.cam: subdomain: xx-yyy
For domain xx4yyy.domain.cam: subdomain not matched
For domain abcde.domain.com: subdomain not matched
For domain my-sub-domain.domain.org: subdomain: my-sub-domain
精彩评论