如何仅使用preg_match允许单个减号?

时间:2014-06-09 11:31:49

标签: php regex preg-match

如何仅使用preg_match?

允许单个连字符

我的例子不起作用。

function isSubdomainValid($subdomain){
    $patt = '/^([a-z0-9]+-?[a-z0-9]+[a-z0-9]+)+$/i';
    if (preg_match($patt, $subdomain)){
        return true;
    }
    return false;
}

例如,

helloworld                   ok
hello-world                  ok
hello-world-again            ok
hello--world                 not ok
hello-world--again--         not ok
--hello-world--again         not ok
hello-world--again-          not ok
-hello-world-again           not ok

2 个答案:

答案 0 :(得分:1)

这个作品很棒!

function isSubdomainValid($subdomain){
    $patt = '/^([a-z0-9]+[a-z0-9-]+[a-z0-9]+)+$/i';
    $patt2 = '/-{2}/';
    if (preg_match($patt, $subdomain)){
        if (!preg_match($patt2, $subdomain)){
            return true;
        }
    }
    return false;
}

答案 1 :(得分:0)

<?php
 $patt = '/^([a-z0-9](+-){0,}[a-z0-9]+[a-z0-9]+)+$/i';
?>

试试这个 来源“http://www.regular-expressions.info/repeat.html