Prevent double space when entering username

后端 未结 2 1035
夕颜
夕颜 2021-01-07 08:32

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[         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-07 09:03

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

提交回复
热议问题