PHP 正则表达式,表示字符串中最多两个特殊字符


PHP Regular expression for maximum of two special characters in a string

我正在验证PHP中的一个文本字段,其中我允许字母,数字,点,破折号和下划线。 但我最多想要两个点和/或两个破折号和/或两个下划线。 我该怎么做? 如果这不可行,那么我怎么会允许上述任何一种中的最多两种呢?

我会这样做。

function checkString($string){
    $c1 = substr_count($string, '.');
    $c2 = substr_count($string, '-');
    $c3 = substr_count($string, '_');
    if($c1 <= 2 && $c2 <= 2 && $c3 <= 2){
        return true;
    }else{
        return false;
    }
}