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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改