PHP - 确保字符串没有空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8251897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - make sure string has no whitespace
提问by user547794
How can I check if a PHP string contains any white space? I want to check if white space is in there, and then echo back an error message if true
如何检查 PHP 字符串是否包含任何空格?我想检查那里是否有空格,如果为真,则回显一条错误消息
if(strlen($username) == whitespace ){
echo "<center>Your username must not contain any whitespace</center>";
回答by bensiu
if ( preg_match('/\s/',$username) ) ....
回答by Mauro Mascia
This solution is for the inverse problem: to know if a string contains at least one word.
这个解决方案是针对逆问题的:知道一个字符串是否至少包含一个单词。
/**
* Check if a string contains at least one word.
*
* @param string $input_string
* @return boolean
* true if there is at least one word, false otherwise.
*/
function contains_at_least_one_word($input_string) {
foreach (explode(' ', $input_string) as $word) {
if (!empty($word)) {
return true;
}
}
return false;
}
If the function return false there are no words in the $input_string. So, you can do something like that:
如果函数返回 false,则 $input_string 中没有单词。所以,你可以做这样的事情:
if (!contains_at_least_one_word($my_string)) {
echo $my_string . " doesn't contain any words.";
}
回答by Bouni
Try this too :
也试试这个:
if (count(explode(' ', $username)) > 1) {
// some white spaces are there.
}
回答by Raptor
Try this method:
试试这个方法:
if(strlen(trim($username)) == strlen($username)) {
// some white spaces are there.
}
回答by Reiozaghi
Try this:
尝试这个:
if ( preg_match('/\s/',$string) ){
echo "yes $string contain whitespace";
} else {
echo "$string clear no whitespace ";
}
回答by Adnane ZA
Other Method :
其他方法:
$string = "This string have whitespace";
if( $string !== str_replace(' ','',$string) ){
//Have whitespace
}else{
//dont have whitespace
}
回答by Frederik Krautwald
PHP provides a built-in functionctype_space( string $text )
to check for whitespace characters. However, ctype_space()
checks if everycharacter of the string creates a whitespace. In your case, you could make a function similar to the following to check if a string has whitespace characters.
PHP 提供了一个内置函数ctype_space( string $text )
来检查空白字符。但是,ctype_space()
检查字符串的每个字符是否都创建了空格。在您的情况下,您可以创建一个类似于以下内容的函数来检查字符串是否包含空格字符。
/**
* Checks string for whitespace characters.
*
* @param string $text
* The string to test.
* @return bool
* TRUE if any character creates some sort of whitespace; otherwise, FALSE.
*/
function hasWhitespace( $text )
{
for ( $idx = 0; $idx < strlen( $text ); $idx += 1 )
if ( ctype_space( $text[ $idx ] ) )
return TRUE;
return FALSE;
}