dtukyb8095 2014-02-26 17:26
浏览 62
已采纳

输入用户名时防止双倍空间

When users register to my website I want to allow them to use spaces in their username, but only one space per word.

My current code:

$usor = $_POST['usernameone'];
$allowed = "/[^a-z0-9 ]/i";
$username = preg_replace($allowed,"",$usor);
$firstlettercheck = $username[0];
$lastlettercheck = substr("$username", -1);

if ($firstlettercheck == " " or $lastlettercheck == " ")
{
echo "Usernames can not contain a space at start/end of username."; 
}

What do I need to add to ensure there is only one space entered inebtween words of the username?

  • 写回答

2条回答

  • dqd2800 2014-02-26 17:32
    关注

    You can use a regex of (^\s+|\s{2,}|\s+$) to validate using preg_match:

    if (preg_match('/(^\s+|\s{2,}|\s+$)/', $username)) {
        echo "Usernames can not contain a space at start/end of username and can't contain double spacing."; 
    }
    

    REGEX DEMO

    Autopsy:

    • (^\s+|\s{2,}|\s+$):
      • ^\s+ matches 1 or more white-space characters (space/tab/newline) in the start of the string
      • | OR:
      • \s{2,} matches 2 or more white-space characters (space/tab/newline) anywhere in the string
      • | OR:
      • \s+$ matches 1 or more white-space characters (space/tab/newline) in the end of the string

    If you wish to test them separately instead:

    if (preg_match('/(^\s+|\s+$)/', $username)) {
        echo 'Usernames can not contain a space at start/end of username.'; 
    } else if (preg_match('/\s{2,}/', $username)) {
        echo 'Usernames can not contain double spacing.';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿