输入用户名时防止双空格 [英] Prevent double space when entering username

查看:108
本文介绍了输入用户名时防止双空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户注册到我的网站时,我希望允许他们在用户名中使用空格,但每个单词只能使用一个空格.

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

我当前的代码:

$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?

推荐答案

您可以使用 (^\s+|\s{2,}|\s+$) 的正则表达式来验证使用 preg_match:

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

正则表达式演示

尸检:

  • (^\s+|\s{2,}|\s+$):
    • ^\s+ 匹配字符串开头的1个或多个空白字符(空格/制表符/换行符)
    • | 或:
    • \s{2,} 匹配字符串中任意位置的 2 个或更多空白字符(空格/制表符/换行符)
    • | 或:
    • \s+$ 匹配字符串末尾的1个或多个空白字符(空格/制表符/换行符)
    • (^\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.';
      }
      

      这篇关于输入用户名时防止双空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆