简体   繁体   中英

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

I am validating a text field in PHP in which I allow letters, numbers, dots, dashes, and underscore. But I want a maximum of two dots and/or two dashes and/or two underscores. How would I do that? And if that's not doable, then how would I allow maximum of two of any of the above?

I would do it this way.

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;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM