Prevent double space when entering username

半世苍凉 提交于 2019-12-30 07:33:50

问题


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?


回答1:


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



回答2:


Use the following:

$username = preg_replace('/[\s]+', " ", $usor);

That will replace multiple spaces with a single space.



来源:https://stackoverflow.com/questions/22048759/prevent-double-space-when-entering-username

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!