【问题标题】:Prevent double space when entering username输入用户名时防止出现双空格
【发布时间】:2014-03-29 17:11:19
【问题描述】:

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

我当前的代码:

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

我需要添加什么以确保在用户名的单词之间只输入一个空格?

【问题讨论】:

  • 您应该选择警告用户和执行自动更正。

标签: php string replace preg-replace space


【解决方案1】:

您可以使用(^\s+|\s{2,}|\s+$) 的正则表达式来验证使用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

尸检

  • (^\s+|\s{2,}|\s+$):
    • ^\s+ 匹配字符串开头的 1 个或多个空白字符(空格/制表符/换行符)
    • | 或者:
    • \s{2,} 匹配字符串中任意位置的 2 个或更多空白字符(空格/制表符/换行符)
    • | 或者:
    • \s+$ 匹配字符串末尾的 1 个或多个空白字符(空格/制表符/换行符)

如果您想单独测试它们:

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

【讨论】:

  • @Mr.Smith 正则表达式可以做到这一点。如果您愿意,请查看演示。他从来没有提到剥离,而是给出了一个错误。
  • 您介意向我解释一下 '/(^\s+|\s{2,}|\s+$)/' 中的每个部分是什么吗?会很棒
  • @StevenWilmot 我已经为你添加了尸检。 :-)
【解决方案2】:

使用以下内容:

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

这将用一个空格替换多个空格。

【讨论】:

  • 用户将拥有一个他们不需要的用户名,并且无法登录。
  • 但这就是 OP 要求的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 2019-09-05
  • 1970-01-01
  • 2012-05-05
  • 2011-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多