Home > Backend Development > PHP Tutorial > 只允许汉字,字母,数字和停横线组合的正则

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

WBOY
Release: 2016-06-13 13:26:50
Original
1553 people have browsed it

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

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

Copy after login

以上的验证无法屏蔽中文标点,空格等特殊字符
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"; 
    } 
    }

Copy after login

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



------解决方案--------------------
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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template