>  기사  >  백엔드 개발  >  只允许汉字,字母,数字和停横线组合的正则

只允许汉字,字母,数字和停横线组合的正则

WBOY
WBOY원래의
2016-06-13 13:26:501506검색

只允许汉字,字母,数字和下横线组合的正则

PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
    if(isset($_GET["username"])){
    $username=$_GET["username"];
    $str=mb_strlen($username);
    if(!preg_match("/^[".chr(0xa1)."-".chr(0xff)." | a-z | 0-9 | A-Z| \_]+$/",$username) || $str16) 
    { 
    echo "1"; 
    }
    }


以上的验证无法屏蔽中文标点,空格等特殊字符
PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
if(isset($_GET["username"])){
    $username=$_GET["username"];
    $str=mb_strlen($username);
    if(!preg_match("/(([\xB0-\xF7][\xA1-\xFE])|([\x81-\xA0][\x40-\xFE])|([\xAA-\xFE][\x40-\xA0])|(\w))+/",$username) || $str16) 
    { 
    echo "1"; 
    } 
    }


以上的验证无法屏蔽空格,中文与中文标点组合,有没只能由汉字,字母,数字和下横线组合的验证,这里的汉字是指纯汉字,不包括中文标点符号空格等特殊字符。 



------解决方案--------------------
PHP code
$s ='我是ss中_文';
$p='/^[\x{4e00}-\x{9fa5}\w]+$/u'; 
$bool=preg_match($p,$s);
var_dump($bool);   // 1
<br><font color="#e78608">------解决方案--------------------</font><br>
你这是 gbk 编码的<br>if(preg_match('/^(?:\w|[\x80-\x9f\xb0-\xff].)+$/', $s))<br><br>对于 utf-8 编码要简单些<br>if(preg_match('^\w+$/u'))<br> <div class="clear">
                 
              
              
        
            </div>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.