[英]PHP - make sure string has no whitespace
如何檢查 PHP 字符串是否包含任何空格? 我想檢查那里是否有空格,如果為真,則回顯錯誤消息
if(strlen($username) == whitespace ){
echo "<center>Your username must not contain any whitespace</center>";
if ( preg_match('/\s/',$username) ) ....
也試試這個:
if (count(explode(' ', $username)) > 1) {
// some white spaces are there.
}
這個解決方案是針對逆問題的:知道一個字符串是否至少包含一個單詞。
/**
* 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;
}
如果函數返回 false,則 $input_string 中沒有單詞。 所以,你可以做這樣的事情:
if (!contains_at_least_one_word($my_string)) {
echo $my_string . " doesn't contain any words.";
}
嘗試這個:
if ( preg_match('/\s/',$string) ){
echo "yes $string contain whitespace";
} else {
echo "$string clear no whitespace ";
}
試試這個方法:
if(strlen(trim($username)) == strlen($username)) {
// some white spaces are there.
}
其他方法:
$string = "This string have whitespace";
if( $string !== str_replace(' ','',$string) ){
//Have whitespace
}else{
//dont have whitespace
}
我發現了另一個很好的函數,它可以很好地搜索字符串中的一些字符集 - strpbrk
if (strpbrk($string, ' ') !== false) {
echo "Contain space";
} else {
echo "Doesn't contain space";
}
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.