如何从输入表单提交中删除空格

How to remove spaces from input form submit

所以我有一个输入表单,用户可以在其中输入用户名,提交后,网站会根据用户名收集信息,但是,如果用户名中有 space,则用户名变为无效(不存在)。我如何在 PHP 中添加一个行为来删除所有 space,这样最终提交的用户名就不会是 john doe,而是 johndoe


这是我的表单代码:

<form action="php.php" method="GET">
  <div class="form-group">
    <label for="username">Username:</label>
    <input type="text" class="form-control" id="username" name="username" placeholder="Enter username" required>
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>

这里是 php.php 文件代码:

//I GUESS THIS IS WHERE THE TRIMMING SHOULD HAPPEN?
<?php
//error_reporting(E_ALL & ~E_NOTICE);
// Load the username from somewhere
if (
$username = $_GET["username"]
) {
    //do nothing 
} else {
    //$username = "notch";
  echo "Oops! Something went wrong!";
}
?>

使用字符串替换函数将字符串中所有出现的 space 替换为空字符串(无):

$string = 'My Name';
$noSpaces = str_replace(' ', '', $string);
echo $noSpaces; // echos 'MyName'

1. 如果您在谈论前导或尾随空格,请使用 trim() 函数。

$username =trim($username);

2 但是如果你在谈论中间空间然后用 preg_replace():-

$username = preg_replace('/\s+/', ' ', $username);

3 你也可以用 str_replace():-

$username = str_replace(' ','',$username);

注意:-这里$username是您要使用的用户名。

您还可以将第一个与第二个或第三个合并,以获得完全干净的用户名,没有前导尾随和中间空格。像这样:-

$username = trim(preg_replace('/\s+/', ' ', $username));

上面有一点错别字,但是在Whosebug中的编辑必须至少6个字符,所以我做了那个无意义的词...