检查字符串中是否有空格


Check for space in string

我正在为我的网站注册页面工作,我想格式化用户名字段,以防止用户提交用户名之间的空间。例如,如果用户提交了一个用户名,如"space man",我想将其更改为"space_man"。我的工作与php,我怎么去它。

嗯,最好的方法之一是在客户端和服务器端同时进行验证。

在客户端,必须使用javascript进行验证。

obj.value.replace(" ", "_");
alert("Invalid username. Changing space to underscore.");

在php的服务器端也做同样的事情。

strstr($_POST['username'],' ','_');

如果"空间"对你来说是唯一重要的事情,那么这是可以做到的。否则你就得写所有的规则

str_replace(' ','_',$input);

这是一个简单的字符串替换:

$username = str_replace(" ", "_", $username);

我当然欣赏strtr:

strtr($_GET['username'],' ','_');

它也很强大

strtr($_GET['username'],array(' '=>'_',"'t"=>'_'));

str_replace ,显然,作品。

str_replace(' ', '_', $txtUserName);

看看http://www.php.net/str_replace -我相信你会从那里弄清楚的。当然,您想要验证的内容还有很多,因此最好使用白名单过滤(说出您允许的内容,而不是不允许的内容),就像下面这样:

if (! preg_match('/^[a-z0-9]{3,32}$/', $_POST['username'])) {
    die('Invalid username'); // of course, dying is not good either, just for the example
}