我怎么能阻止这个名字的空间?

时间:2017-04-13 19:03:47

标签: php substr

目前,我试图阻止我的客户在我的网站上创建帐户时使用名称空间。

他们可以注册为"弗雷德",它应该是不可能的,应该只是" Fred"而不是名字后的空格。

我尝试使用:

if(substr($name_to_check, -1) == " ")
    return false;

但似乎没有用。

感谢。

2 个答案:

答案 0 :(得分:1)

你可以使用php trim()

trim - 从字符串的开头和结尾去掉空格(或其他字符)

如果从字符串的开头删除空格(或其他字符)

ltrim($name_to_check);

如果从字符串末尾删除空格(或其他字符)

rtrim($name_to_check);

如果你想删除一些部分。从字符串两边移动字符("他"在"你好"和" d!"在& #34;世界&#34):

<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>

然后输出

Hello World!
llo Worl

类似这样的事情

<?php
$str = " Hello World! ";
echo $str.": Without trim";
echo "<br>";
echo trim($str).": With trim";
?>

然后输出

Hello World! : Without trim
Hello World!: With trim

了解更多信息

https://www.w3schools.com/php/func_string_trim.asp

答案 1 :(得分:1)

您应该使用from this answer代替。这样做是标准方式,也会阻止您使用不必要的if

trim()的使用示例:

<?php

$text   = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = trim($text);
var_dump($trimmed);

$trimmed = trim($text, " \t.");
var_dump($trimmed);

$trimmed = trim($hello, "Hdle");
var_dump($trimmed);

$trimmed = trim($hello, 'HdWr');
var_dump($trimmed);

// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);

?>