使用正则表达式没有前沿空白的汉字?

时间:2014-01-23 03:54:17

标签: regex preg-match

  

这个问题错了。正则表达式实际上是我想要的。我错过了一个   在正则表达式检查源代码之前,“ trim()”。


原始问题:

我不知道怎么做。这个正则表达式在中文字符之间不允许有空格,但如果你在前面放一个空格,它就会通过。

if(preg_match('/^[\x{4e00}-\x{9fa5}A-Za-z]{1,7}$/u',$username)){

正如你所看到的,我想要中文,英文字母,下划线,没有别的。

1 个答案:

答案 0 :(得分:0)

试试这个正则表达式:

/^[\x{4e00}-\x{9fa5}a-z _]{1,7}$/ui

示例代码

<?php
    // Since PHP doesn't support Unicode escape sequence, so I use json_decode here for typing random chinese chars
    $username = json_decode('" \u4e00 \u4e01f_o"');
    echo preg_match('/^[\x{4e00}-\x{9fa5}a-z _]{1,7}$/ui',$username); // ouputs 1
?>

演示

http://phpfiddle.org/lite/code/c5t-zr2